package com.seegw.shaphar;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaweb.admin.constant.FormtableMain12974Constant;
import com.javaweb.admin.entity.*;
import com.javaweb.admin.entity.kdltrans.KdlTransDto;
import com.javaweb.admin.entity.kdltrans.KdlTransVendor;
import com.javaweb.admin.entity.kdltrans.KdlTransVendorOper;
import com.javaweb.admin.entity.kdltrans.KdlTransVendorTruck;
import com.javaweb.admin.mapper.*;
import com.javaweb.admin.mapper.kdltrans.KdlTransVendorMapper;
import com.javaweb.admin.mapper.kdltrans.KdlTransVendorOperMapper;
import com.javaweb.admin.mapper.kdltrans.KdlTransVendorTruckMapper;
import com.javaweb.admin.query.*;
import com.javaweb.admin.service.*;
import com.javaweb.admin.vo.kdlgm.KdlGMVo;
import com.javaweb.admin.vo.kdlinventory.KdlInventoryVo;
import com.javaweb.admin.vo.kdlpod.KdlPODVo;
import com.javaweb.admin.vo.kdlqfffeedback.KdlQffFeedbackVo;
import com.javaweb.admin.vo.kdlrgr.KdlRGRVo;
import com.javaweb.admin.vo.transreport.KdlMaintainReportVo;
import com.javaweb.admin.vo.transreport.KdlTransReportVo;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.config.CommonConfig;
import com.javaweb.common.config.DataSourceType;
import com.javaweb.common.config.DynamicDataSource;
import com.javaweb.common.config.SpecifyDataSource;
import com.javaweb.common.utils.*;
import com.javaweb.system.constant.Constants;
import com.javaweb.system.service.IDictDataService;
import com.javaweb.system.utils.ShiroUtils;
import com.seegw.shaphar.generalout.GeneralOutBodys;
import com.seegw.shaphar.generalout.NCGeneralOut;
import com.seegw.shaphar.gm.NCWhstrans;
import com.seegw.shaphar.gm.WhstransBodys;
import com.seegw.shaphar.purchasein.NCPurchaseIn;
import com.seegw.shaphar.purchasein.PurchaseInBodys;
import com.seegw.shaphar.saleout.SaleOut2NC;
import com.sphchina.esb.webservice.ISendToReviewLog;
import com.sphsine.bip.SHYPConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
public class KDLServiceImpl implements IKDLService{
    private static final Logger log = LoggerFactory.getLogger(KDLServiceImpl.class);
    @Autowired
    INcServiceLogService ncServiceLogService;

    @Autowired
    KDLCustomerMapper kdlCustomerMapper;

    @Autowired
    KDLSupplierMapper kdlSupplierMapper;

    @Autowired
    KDLCustomerLogMapper kdlCustomerLogMapper;

    @Autowired
    KDLSupplierLogMapper kdlSupplierLogMapper;

    @Autowired
    KDLMaterialMapper kdlMaterialMapper;

    @Autowired
    KDLMaterialLogMapper kdlMaterialLogMapper;

    @Autowired
    NCPOOrderMapper ncpoOrderMapper;
    @Autowired
    NCSOOrderMapper ncsoOrderMapper;
    @Autowired
    NCGeneraloutHMapper ncGeneraloutHMapper;

    @Autowired
    NCGeneralinHMapper ncGeneralinHMapper;
    @Autowired
    KdlPurchaseinMapper kdlPurchaseinMapper;

    @Autowired
    KdlPurchaseinBMapper kdlPurchaseinBMapper;

    @Autowired
    KdlPurchaseinReturnMapper kdlPurchaseinReturnMapper;

    @Autowired
    KdlPurchaseinReturnBMapper kdlPurchaseinReturnBMapper;

    @Autowired
    KdlZBFEMapper kdlZBFEMapper;

    @Autowired
    KdlZBFEBMapper kdlZBFEBMapper;

    @Autowired
    KdlSaleOutMapper kdlSaleOutMapper;

    @Autowired
    KdlSaleOutQcMapper kdlSaleOutQcMapper;

    @Autowired
    KdlSaleOutBMapper kdlSaleOutBMapper;

    @Autowired
    KdlGMMapper kdlGMMapper;

    @Autowired
    KdlMaraMapper kdlMaraMapper;

    @Autowired
    KdlCoaMapper kdlCoaMapper;

    @Autowired
    KdlInventoryMapper kdlInventoryMapper;

    @Autowired
    KdlInventoryDayMapper kdlInventoryDayMapper;
    @Autowired
    KdlQffFeedbackMapper kdlQffFeedbackMapper;
    @Autowired
    KdlQffAttachMapper kdlQffAttachMapper;

    @Autowired
    KdlTransReportMapper kdlTransReportMapper;

    @Autowired
    KdlMaintainReportMapper kdlMaintainReportMapper;

    @Autowired
    KdlRGRMapper kdlRGRMapper;
    @Autowired
    KdlPODMapper kdlPODMapper;
    @Autowired
    KdlStoredocMapper kdlStoredocMapper;

    @Autowired
    KdlTransVendorMapper kdlTransVendorMapper;

    @Autowired
    KdlTransVendorOperMapper kdlTransVendorOperMapper;
    @Autowired
    KdlTransVendorTruckMapper kdlTransVendorTruckMapper;

    @Autowired
    private ISendToReviewLog sendToReviewLog;

    @Autowired
    private KdlInspectionresultStatusMapper kdlInspectionresultStatusMapper;

    @Autowired
    private KdlZ05kdlMapper kdlZ05kdlMapper;

    @Autowired
    private KdlZ05kdlBMapper kdlZ05kdlBMapper;
    @Autowired
    private IDictDataService dictDataService;

    @Autowired
    private KdlSineGoodsmovementMapper kdlSineGoodsmovementMapper;

    @Autowired
    private KdlSineSoOutboundMapper kdlSineSoOutboundMapper;

    @Autowired
    private KdlNcOnhandMapper kdlNcOnhandMapper;

    @Autowired
    SFTPUtil ftpUtil;

    @Autowired
    private ScmBatchCodeMapper scmBatchCodeMapper;

    @Autowired
    private KdlPurchaseweMapper kdlPurchaseweMapper;
    @Autowired
    private KdlPurchaseweBMapper kdlPurchaseweBMapper;

    @Autowired
    private INcTaskLogService iNcTaskLogService;

    @Autowired
    private IKdlGMService kdlGMService;
    @Autowired
    private IKdlSaleOutQcService kdlSaleOutQcService;
    @Autowired
    private IKdlPurchaseinReturnService kdlPurchaseinReturnService;
    @Autowired
    private IKdlZ05kdlService kdlZ05kdlService;
    @Autowired
    private IKdlPurchaseinService kdlPurchaseinService;
    @Autowired
    private IKdlPurchaseweService kdlPurchaseweService;
    @Autowired
    private FormtableMain12974Mapper formtableMain12974Mapper;
    @Autowired
    private KdlHCMapper kdlHCMapper;
    @Autowired
    NcOnhandMapper ncOnhandMapper;

    /**
     * 根据字典编码及字典项名称获取NC回传接口的制单人、审批人
     * @param dataType 字典项名称，康德乐接口类型
     * @return NC系统用户的主键
     */
    private String getNCUserId(String dataType)
    {
        DynamicDataSource.setDataSource("system");
        String ncUserId = dictDataService.getNCUserId(dataType);

        return ncUserId;
    }

    /**
     * 根据字典编码及字典项名称获取NC回传接口的制单人、审批人
     * @param dataType 字典项名称，康德乐接口类型
     * @return NC系统用户的主键
     */
    private String getNCUserId(String dataType,DataSourceType dataSourceType)
    {
        DynamicDataSource.setDataSource("system");
        String ncUserId = dictDataService.getNCUserId(dataType);
        DynamicDataSource.setDataSource(dataSourceType.getName());
        return ncUserId;
    }


    /**
     * 查询字段状态值
     *
     * @param dicCode
     * @param dicDataCode
     * @param dataSourceType
     * @return
     */
    private String getDicStatus(String dicCode, String dicDataCode, DataSourceType dataSourceType) {
        DynamicDataSource.setDataSource("system");
        String status = dictDataService.getDicStatus(dicCode, dicDataCode);
        DynamicDataSource.setDataSource(dataSourceType.getName());
        return status;
    }
    @Override
    public String[] getBillType(String dictCode) {
        String[] result= dictDataService.getBillType(dictCode);
        return result;
    }

    @Override
    @SpecifyDataSource(DataSourceType.SINESYS)
    public JsonResult getGeneralOutBillType() {
        return JsonResult.success(ncGeneraloutHMapper.getBillTypeList());
    }

    @Override
    @SpecifyDataSource(DataSourceType.SINESYS)
    public JsonResult getGeneralInBillType() {
        return JsonResult.success(ncGeneralinHMapper.getBillTypeList());
    }

    private String isSupplierDataUpdated(KDLSupplier ncSupplier, KDLSupplier localSupplier)
    {
        StringBuilder sb = new StringBuilder();
        if(StringUtils.isNull(ncSupplier) || StringUtils.isNull(localSupplier)) return "";
        String ncCustomername = ncSupplier.getSuppliername();
        String ncAddress = ncSupplier.getAddress();
        String ncNation = ncSupplier.getNation();
        String ncRegion = ncSupplier.getRegion();
        String ncTranszone = ncSupplier.getTranszone();
        String ncProfession = ncSupplier.getProfession();
        String ncCity = ncSupplier.getCity();
        if(!ncCustomername.equals(localSupplier.getSuppliername()))
        {
            sb.append("供应商名称变更:"+localSupplier.getSuppliername()+"->"+ncCustomername);
        }
        if(!ncAddress.equals(localSupplier.getAddress()))
        {
            sb.append("供应商地址变更:"+localSupplier.getAddress()+"->"+ncAddress);
        }
        if(!ncNation.equals(localSupplier.getNation()))
        {
            sb.append("国家变更:"+localSupplier.getNation()+"->"+ncNation);
        }
        if(!ncRegion.equals(localSupplier.getRegion()))
        {
            sb.append("地区变更:"+localSupplier.getNation()+"->"+ncNation);
        }
        if(!ncTranszone.equals(localSupplier.getTranszone()))
        {
            sb.append("运输区域变更:"+localSupplier.getTranszone()+"->"+ncTranszone);
        }
        if(!ncProfession.equals(localSupplier.getProfession()))
        {
            sb.append("行业变更:"+localSupplier.getProfession()+"->"+ncProfession);
        }
        if(!ncCity.equals(localSupplier.getCity()))
        {
            sb.append("城市变更:"+localSupplier.getCity()+"->"+ncCity);
        }
        if(!ncSupplier.getFcbz().equals(localSupplier.getFcbz()))
        {
            sb.append("封存状态变更:"+ncSupplier.getFcbz()+"->"+localSupplier.getFcbz());
        }
        if(!ncSupplier.getRestcode().equals(localSupplier.getRestcode()))
        {
            sb.append("码上放心编码变更:"+localSupplier.getRestcode()+"->"+ncSupplier.getRestcode());
        }

        return sb.toString();

    }

    private String isMaterialDataUpdated(KDLMaterial ncMaterial,KDLMaterial localMaterial)
    {
        StringBuilder sb = new StringBuilder();
        if(StringUtils.isNull(ncMaterial) || StringUtils.isNull(localMaterial)) return "";
        String ncMaterialDes = ncMaterial.getMaterialdes();
        String ncMaterialGroup = ncMaterial.getMaterialgroup();
        String ncProductGroup = ncMaterial.getProductgroup();


        if(!ncMaterialDes.equals(localMaterial.getMaterialdes()))
        {
            sb.append("物料描述变更:"+localMaterial.getMaterialdes()+"->"+ncMaterialDes);
        }
        if(!ncMaterialGroup.equals(localMaterial.getMaterialgroup()))
        {
            sb.append("物料组变更:"+localMaterial.getMaterialgroup()+"->"+ncMaterialGroup);
        }
        if(!ncProductGroup.equals(localMaterial.getProductgroup()))
        {
            sb.append("产品组变更:"+localMaterial.getProductgroup()+"->"+ncProductGroup);
        }
        if(!ncMaterial.getLregistno().equals(localMaterial.getLregistno()))
        {
            sb.append("注册证号变更:"+localMaterial.getLregistno()+"->"+ncMaterial.getLregistno());
        }
        if(!ncMaterial.getLexpireddate().equals(localMaterial.getLexpireddate()))
        {
            sb.append("有效期变更:"+localMaterial.getLexpireddate()+"->"+ncMaterial.getLexpireddate());
        }
        if(!ncMaterial.getBasicunit().equals(localMaterial.getBasicunit()))
        {
            sb.append("基本单位变更:"+localMaterial.getBasicunit()+"->"+ncMaterial.getBasicunit());
        }
        if(!ncMaterial.getSalesunit().equals(localMaterial.getSalesunit()))
        {
            sb.append("销售单位变更:"+localMaterial.getSalesunit()+"->"+ncMaterial.getSalesunit());
        }
        if(!ncMaterial.getOriginalcountry().equals(localMaterial.getOriginalcountry()))
        {
            sb.append("物料原产地变更:"+localMaterial.getOriginalcountry()+"->"+ncMaterial.getOriginalcountry());
        }
        if(!ncMaterial.getTransportationitemgroup().equals(localMaterial.getTransportationitemgroup()))
        {
            sb.append("运输物料组变更:"+localMaterial.getTransportationitemgroup()+"->"+ncMaterial.getTransportationitemgroup());
        }

        if(!ncMaterial.getBatch().equals(localMaterial.getBatch()))
        {
            sb.append("是否批次管理变更:"+localMaterial.getBatch()+"->"+ncMaterial.getBatch());
        }
        if(!ncMaterial.getCategory().equals(localMaterial.getCategory()))
        {
            sb.append("类别变更:"+localMaterial.getCategory()+"->"+ncMaterial.getCategory());
        }
        if(!ncMaterial.getPurchaseunit().equals(localMaterial.getPurchaseunit()))
        {
            sb.append("主计量单位变更:"+localMaterial.getPurchaseunit()+"->"+ncMaterial.getPurchaseunit());
        }
        if(!ncMaterial.getManufacturername().equals(localMaterial.getManufacturername()))
        {
            sb.append("生产厂商变更:"+localMaterial.getManufacturername()+"->"+ncMaterial.getManufacturername());
        }
        if(!ncMaterial.getStoragecondition().equals(localMaterial.getStoragecondition()))
        {
            sb.append("存储条件:"+localMaterial.getStoragecondition()+"->"+ncMaterial.getStoragecondition());
        }

        if(!ncMaterial.getComdescription().equals(localMaterial.getComdescription()))
        {
            sb.append("物料通用名称变更:"+localMaterial.getComdescription()+"->"+ncMaterial.getComdescription());
        }
        if(!ncMaterial.getMaterialform().equals(localMaterial.getMaterialform()))
        {
            sb.append("剂型变更:"+localMaterial.getMaterialform()+"->"+ncMaterial.getMaterialform());
        }
        if(!ncMaterial.getMaterialspec().equals(localMaterial.getMaterialspec()))
        {
            sb.append("规格变更:"+localMaterial.getMaterialspec()+"->"+ncMaterial.getMaterialspec());
        }
        if(!ncMaterial.getProductgroupcode().equals(localMaterial.getProductgroupcode()))
        {
            sb.append("产品大类变更:"+localMaterial.getProductgroupcode()+"->"+ncMaterial.getProductgroupcode());
        }
        if(!ncMaterial.getGspcategorycode().equals(localMaterial.getGspcategorycode()))
        {
            sb.append("新GSP分类变更:"+localMaterial.getNwegspcategorycode()+"->"+ncMaterial.getNwegspcategorycode());
        }
        if(!ncMaterial.getNwegspcategorycode().equals(localMaterial.getNwegspcategorycode()))
        {
            sb.append("GSP分类变更:"+localMaterial.getGspcategorycode()+"->"+ncMaterial.getGspcategorycode());
        }
        if(!ncMaterial.getEcode().equals(localMaterial.getEcode()))
        {
            sb.append("电子监管码变更:"+localMaterial.getEcode()+"->"+ncMaterial.getEcode());
        }
        if(!ncMaterial.getMedicinecode().equals(localMaterial.getMedicinecode()))
        {
            sb.append("药品分类变更:"+localMaterial.getMedicinecode()+"->"+ncMaterial.getMedicinecode());
        }
        if(!ncMaterial.getImploc().equals(localMaterial.getImploc()))
        {
            sb.append("进口或本地变更:"+localMaterial.getImploc()+"->"+ncMaterial.getImploc());
        }
        if(!ncMaterial.getCaution().equals(localMaterial.getCaution()))
        {
            sb.append("运动员慎用变更:"+localMaterial.getCaution()+"->"+ncMaterial.getCaution());
        }
        if(!ncMaterial.getPrfrq().equals(localMaterial.getPrfrq()))
        {
            sb.append("养护检查间隔时间变更:"+localMaterial.getPrfrq()+"->"+ncMaterial.getPrfrq());
        }
        if(ncMaterial.getRegistrationapproveddate()!=null && !ncMaterial.getRegistrationapproveddate().equals(localMaterial.getRegistrationapproveddate()))
        {
            sb.append("注册证批准日期变更:"+localMaterial.getRegistrationapproveddate()+"->"+ncMaterial.getRegistrationapproveddate());
        }
        if(!ncMaterial.getHumidityconditions().equals(localMaterial.getHumidityconditions()))
        {
            sb.append("湿度条件变更:"+localMaterial.getHumidityconditions()+"->"+ncMaterial.getHumidityconditions());
        }
        if(!ncMaterial.getTemp().equals(localMaterial.getTemp()))
        {
            sb.append("温度条件变更:"+localMaterial.getTemp()+"->"+ncMaterial.getTemp());
        }
        if(!ncMaterial.getRegistrationfilingapplicantname().equals(localMaterial.getRegistrationfilingapplicantname()))
        {
            sb.append("上市许可持有人变更:"+localMaterial.getRegistrationfilingapplicantname()+"->"+ncMaterial.getRegistrationfilingapplicantname());
        }
        if(!ncMaterial.getCommissionedmanufacturername().equals(localMaterial.getCommissionedmanufacturername()))
        {
            sb.append("委托制造商变更:"+localMaterial.getCommissionedmanufacturername()+"->"+ncMaterial.getCommissionedmanufacturername());
        }
        if(!ncMaterial.getYzxpj().equals(localMaterial.getYzxpj()))
        {
            sb.append("一致性评价变更:"+localMaterial.getYzxpj()+"->"+ncMaterial.getYzxpj());
        }
//        if(!ncMaterial.getLineNo().equals(localMaterial.getLineNo()))
//        {
//            sb.append("NC主键变更:"+localMaterial.getLineNo()+"->"+ncMaterial.getLineNo());
//        }
        if(!ncMaterial.getZxmeinh().equals(localMaterial.getZxmeinh()))
        {
            sb.append("计量单位变更:"+localMaterial.getZxmeinh()+"->"+ncMaterial.getZxmeinh());
        }
        if(!ncMaterial.getUmrez().equals(localMaterial.getUmrez()))
        {
            sb.append("箱规变更:"+localMaterial.getUmrez()+"->"+ncMaterial.getUmrez());
        }
        if(!ncMaterial.getLength().equals(localMaterial.getLength()))
        {
            sb.append("长度变更:"+localMaterial.getLength()+"->"+ncMaterial.getLength());
        }
        if(!ncMaterial.getWidth().equals(localMaterial.getWidth()))
        {
            sb.append("宽度变更:"+localMaterial.getWidth()+"->"+ncMaterial.getWidth());
        }
        if(!ncMaterial.getHeight().equals(localMaterial.getHeight()))
        {
            sb.append("高度变更:"+localMaterial.getHeight()+"->"+ncMaterial.getHeight());
        }
        return sb.toString();

    }

    /***
     * 判断客户主数据是否修改
     * @param ncCustomer
     * @param localCustomer
     * @return 修改的字段描述
     */

    private String isDataUpdated(KDLCustomer ncCustomer,KDLCustomer localCustomer)
    {
        StringBuilder sb = new StringBuilder();
        if(StringUtils.isNull(ncCustomer) || StringUtils.isNull(localCustomer)) return "";
        String ncCustomername = ncCustomer.getCustomername();
        String ncDeliveryaddress = ncCustomer.getDeliveryaddress();
        String ncNation = ncCustomer.getNation();
        String ncRegion = ncCustomer.getRegion();
        String ncTranszone = ncCustomer.getTranszone();
        String ncProfession = ncCustomer.getProfession();
        String ncCity = ncCustomer.getCity();
        String ncRestCode = ncCustomer.getRestcode();
        if(!ncCustomername.equals(localCustomer.getCustomername()))
        {
            sb.append("客户名称变更:"+localCustomer.getCustomername()+"->"+ncCustomername);
        }
        if(!ncDeliveryaddress.equals(localCustomer.getDeliveryaddress()))
        {
            sb.append("客户地址变更:"+localCustomer.getDeliveryaddress()+"->"+ncDeliveryaddress);
        }
        if(!ncNation.equals(localCustomer.getNation()))
        {
            sb.append("国家变更:"+localCustomer.getNation()+"->"+ncNation);
        }
        if(!ncRegion.equals(localCustomer.getRegion()))
        {
            sb.append("地区变更:"+localCustomer.getNation()+"->"+ncNation);
        }
        if(!ncTranszone.equals(localCustomer.getTranszone()))
        {
            sb.append("运输区域变更:"+localCustomer.getTranszone()+"->"+ncTranszone);
        }
        if(!ncProfession.equals(localCustomer.getProfession()))
        {
            sb.append("行业变更:"+localCustomer.getProfession()+"->"+ncProfession);
        }
        if(!ncCity.equals(localCustomer.getCity()))
        {
            sb.append("城市变更:"+localCustomer.getCity()+"->"+ncCity);
        }
        if(!ncCustomer.getTel().equals(localCustomer.getTel()))
        {
            sb.append("联系电话变更:"+localCustomer.getTel()+"->"+ncCustomer.getTel());
        }
        if(!ncCustomer.getContacts().equals(localCustomer.getContacts()))
        {
            sb.append("联系人变更:"+localCustomer.getContacts()+"->"+ncCustomer.getContacts());
        }
        if(!ncCustomer.getFcbz().equals(localCustomer.getFcbz()))
        {
            sb.append("封存状态变更:"+localCustomer.getFcbz()+"->"+ncCustomer.getFcbz());
        }
        if(!ncCustomer.getRestcode().equals(localCustomer.getRestcode()))
        {
            sb.append("码上放心编码变更:"+localCustomer.getRestcode()+"->"+ncCustomer.getRestcode());
        }
        if(!((StringUtils.isEmpty(ncCustomer.getQcusername())||StringUtils.isEmpty(ncCustomer.getQcusername()))||ncCustomer.getQcusername().equals(localCustomer.getQcusername())))
        {
            sb.append("质量专员变更:"+localCustomer.getQcusername()+"->"+ncCustomer.getQcusername());
        }
        if(!((StringUtils.isEmpty(ncCustomer.getStceg())||StringUtils.isEmpty(ncCustomer.getStceg()))||ncCustomer.getStceg().equals(localCustomer.getStceg())))
        {
            sb.append("统一社会信用代码:"+localCustomer.getStceg()+"->"+ncCustomer.getStceg());
        }
        if(!((StringUtils.isEmpty(ncCustomer.getSpecialcontacts())||StringUtils.isEmpty(ncCustomer.getSpecialcontacts()))||ncCustomer.getSpecialcontacts().equals(localCustomer.getSpecialcontacts())))
        {
            sb.append("特药联系人:"+localCustomer.getSpecialcontacts()+"->"+ncCustomer.getSpecialcontacts());
        }
        return sb.toString();
    }
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncCustomer() {
        //获取最新NCTS
        try {
            String ncts = kdlCustomerMapper.GetMaxNCTS();
            List<KDLCustomer> customerList = kdlCustomerMapper.GetNCCustomerList(ncts);
            KDLCustomer customerLocal;
            Map<String, Object> param = new HashMap<>();
            for (KDLCustomer entity : customerList) {
                entity.setPrincipalid(CommonConfig.kdlCompanyId);
                entity.setOrdertype("ZCUS");
                entity.setType("01");
                entity.setSenddate(DateUtils.getDate());
                entity.setGroupaccount("ZPRC");
                entity.setTs(DateUtils.now());
                param.put("customercode", entity.getCustomercode());
                List<KDLCustomer> list = kdlCustomerMapper.selectByMap(param);
                KDLCustomerLog entityLog = new KDLCustomerLog();

                if (list.size() > 0) {
                    customerLocal = list.get(0);
                    //判断是否修改了相关字段
                    //药厂客户编码、客户名称、客户地址、国家、地区、运输区域、行业、城市代码出现
                    String remark = isDataUpdated(entity, customerLocal);
                    if (!StringUtils.isEmpty(remark)) {
                        entity.setType("02");
                        entity.setStatus(0);
                        entity.setId(customerLocal.getId());
                        BeanUtils.copyProperties(entity, entityLog);
                        entityLog.setRemark(remark);
                        kdlCustomerLogMapper.insert(entityLog);
                    }
                    kdlCustomerMapper.updateById(entity);

                } else {
                    kdlCustomerMapper.insert(entity);
                    BeanUtils.copyProperties(entity, entityLog);
                    kdlCustomerLogMapper.insert(entityLog);

                }
            }
            return JsonResult.success();
        }catch(Exception ex)
        {
            return  JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitSupplier(Integer id) {
        try {
            ClassPathResource classPathResource = new ClassPathResource("kdl/" + "Supplier.xml");
            InputStream inputStream03 = classPathResource.getStream();
            Document document003= XmlUtil.readXML(inputStream03);
            Element elementG=XmlUtil.getRootElement(document003);
            Element Head = XmlUtil.getElement(elementG,"Head");
            Element elementD = XmlUtil.getElement(elementG,"Details");
            Element Detail = XmlUtil.getElement(elementD,"Detail");

            KDLSupplier entity = kdlSupplierMapper.selectById(id);
            if(StringUtils.isNull(entity))
            {
                return JsonResult.error("无效的id:"+id.toString());
            }
            //判断封存状态
            if("Y".equals(entity.getFcbz())){
                return JsonResult.error("供应商已封存，不能上传:"+entity.getSuppliername()+"("+entity.getSuppliercode()+")");
            }

            //初始化提交报文
            CommonUtils.XmlSetNodeContent(Head,"Type",entity.getType());
            CommonUtils.XmlSetNodeContent(Head,"PrincipalID",CommonConfig.kdlCompanyId);
            String senddate = DateUtil.format(DateUtils.dateTime("yyyy-MM-dd",entity.getSenddate()),"yyyyMMdd");
            CommonUtils.XmlSetNodeContent(Head,"SendDate",senddate);

            CommonUtils.XmlSetNodeContent(Detail,"SupplierCode",entity.getSuppliercode());
            CommonUtils.XmlSetNodeContent(Detail,"SupplierName",entity.getSuppliername());
            CommonUtils.XmlSetNodeContent(Detail,"Address",entity.getAddress());
            CommonUtils.XmlSetNodeContent(Detail,"ENAddress",entity.getAddress());
            CommonUtils.XmlSetNodeContent(Detail,"WarehouseAddress",entity.getAddress());
            CommonUtils.XmlSetNodeContent(Detail,"Nation",entity.getNation());
            CommonUtils.XmlSetNodeContent(Detail,"Region",entity.getRegion());
            CommonUtils.XmlSetNodeContent(Detail,"TransZone",entity.getTranszone());
            CommonUtils.XmlSetNodeContent(Detail,"Profession",entity.getProfession());
            CommonUtils.XmlSetNodeContent(Detail,"City",entity.getCity());
            CommonUtils.XmlSetNodeContent(Detail,"Language",entity.getLanguage());
            CommonUtils.XmlSetNodeContent(Detail,"Currency",entity.getCurrency());
            CommonUtils.XmlSetNodeContent(Detail,"Contacts",entity.getContacts());
            CommonUtils.XmlSetNodeContent(Detail,"RestCode",entity.getRestcode());

            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = XmlUtil.toStr(document003);
            log.setSubmitNo(entity.getSuppliercode());

            log.setRequestBody(body);
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox? SHYPConstants.KDL_SUPPLIER_URL_SUFFIX_TEST:SHYPConstants.KDL_SUPPLIER_URL_SUFFIX,"",null,body,CommonConfig.kdlSandbox);
                Document docResult= XmlUtil.readXML(result);
                Element elementGR=XmlUtil.getRootElement(docResult);
                Element headResult = XmlUtil.getElement(elementGR,"Head");
                String resCode = CommonUtils.XmlGetNodeContent(headResult,"FunCode");
                String resRemark = CommonUtils.XmlGetNodeContent(headResult,"Remark");

                log.setResponseBody(result);
                log.setResponseCode(resCode);
                log.setResponseResult(resRemark);
                ncServiceLogService.save(log);
                if("9000".equals(resCode)) {
                    //更新状态标记
                    UpdateWrapper<KDLSupplier> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("status",1).set("kdlts",DateUtils.now()).eq("id",id);
                    kdlSupplierMapper.update(new KDLSupplier(),updateWrapper);
                    return JsonResult.success(result);
                }else{
                    return JsonResult.error(resCode+":"+resRemark);
                }

            }
            catch (Exception ex)
            {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.success(result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncSupplier() {
        //获取最新NCTS
        try{
        String ncts = kdlSupplierMapper.GetMaxNCTS();
        List<KDLSupplier> customerList = kdlSupplierMapper.GetNCSupplierList(ncts);
        KDLSupplier customerLocal;
        Map<String,Object> param = new HashMap<>();
        for (KDLSupplier entity:customerList) {
            entity.setPrincipalid(CommonConfig.kdlCompanyId);
            entity.setOrdertype("ZCUS");
            entity.setType("01");
            entity.setSenddate(DateUtils.getDate());
            entity.setGroupaccount("Z3PL");
            entity.setTs(DateUtils.now());
            param.put("suppliercode",entity.getSuppliercode());
            List<KDLSupplier> list= kdlSupplierMapper.selectByMap(param);
            KDLSupplierLog entityLog =  new KDLSupplierLog();

            if(list.size()>0)
            {
                customerLocal = list.get(0);
                //判断是否修改了相关字段
                //药厂客户编码、客户名称、客户地址、国家、地区、运输区域、行业、城市代码出现
                String remark = isSupplierDataUpdated(entity,customerLocal);
                if(!StringUtils.isEmpty(remark)) {
                    entity.setType("02");
                    entity.setStatus(0);
                    entity.setId(customerLocal.getId());
                    BeanUtils.copyProperties(entity,entityLog);
                    entityLog.setRemark(remark);
                    kdlSupplierLogMapper.insert(entityLog);
                }
                kdlSupplierMapper.updateById(entity);

            }else {
                kdlSupplierMapper.insert(entity);
                BeanUtils.copyProperties(entity,entityLog);
                kdlSupplierLogMapper.insert(entityLog);

            }
        }
        return JsonResult.success();
        }catch(Exception ex)
        {
            return  JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitCustomer(Integer id) {
        try {
            ClassPathResource classPathResource = new ClassPathResource("kdl/" + "Customer.xml");
            InputStream inputStream03 = classPathResource.getStream();
            Document document003= XmlUtil.readXML(inputStream03);
            Element elementG=XmlUtil.getRootElement(document003);
            Element Head = XmlUtil.getElement(elementG,"Head");
            Element elementD = XmlUtil.getElement(elementG,"Details");
            Element Detail = XmlUtil.getElement(elementD,"Detail");

            KDLCustomer entity = kdlCustomerMapper.selectById(id);
            if(StringUtils.isNull(entity))
            {
                return JsonResult.error("无效的id:"+id.toString());
            }
            //判断封存状态
            if("Y".equals(entity.getFcbz())){
                return JsonResult.error("客户已封存，不能上传:"+entity.getCustomername()+"("+entity.getCustomercode()+")");
            }

            //初始化提交报文
            CommonUtils.XmlSetNodeContent(Head,"PrincipalID",CommonConfig.kdlCompanyId);
            CommonUtils.XmlSetNodeContent(Head,"Type",entity.getType());
            String senddate = "";
            if(StringUtils.isEmpty(entity.getSenddate())){
                senddate = DateUtils.dateTime();
            }else {
                senddate = DateUtil.format(DateUtils.dateTime("yyyy-MM-dd", entity.getSenddate()), "yyyyMMdd");
            }
            CommonUtils.XmlSetNodeContent(Head,"SendDate",senddate);

            CommonUtils.XmlSetNodeContent(Detail,"CustomerCode",entity.getCustomercode());
            CommonUtils.XmlSetNodeContent(Detail,"CustomerName",entity.getCustomername());
            CommonUtils.XmlSetNodeContent(Detail,"DeliveryAddress",entity.getDeliveryaddress());
            CommonUtils.XmlSetNodeContent(Detail,"ENAddress",entity.getDeliveryaddress());
            CommonUtils.XmlSetNodeContent(Detail,"WarehouseAddress",entity.getDeliveryaddress());
            CommonUtils.XmlSetNodeContent(Detail,"Nation",entity.getNation());
            CommonUtils.XmlSetNodeContent(Detail,"Region",entity.getRegion());
            CommonUtils.XmlSetNodeContent(Detail,"TransZone",entity.getTranszone());
            CommonUtils.XmlSetNodeContent(Detail,"Profession",entity.getProfession());
            CommonUtils.XmlSetNodeContent(Detail,"City",entity.getCity());
            CommonUtils.XmlSetNodeContent(Detail,"Contacts",entity.getContacts());
            CommonUtils.XmlSetNodeContent(Detail,"Tel",entity.getTel());
            CommonUtils.XmlSetNodeContent(Detail,"RestCode",entity.getRestcode());
            CommonUtils.XmlSetNodeContent(Detail,"STCEG",entity.getStceg());
            CommonUtils.XmlSetNodeContent(Detail,"SpecialContacts",entity.getSpecialcontacts());

            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = XmlUtil.toStr(document003);
            log.setSubmitNo(entity.getCustomercode());

            log.setRequestBody(body);
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox?SHYPConstants.KDL_CUSTOMER_URL_SUFFIX_TEST:SHYPConstants.KDL_CUSTOMER_URL_SUFFIX,"",null,body,CommonConfig.kdlSandbox);
                Document docResult= XmlUtil.readXML(result);
                Element elementGR=XmlUtil.getRootElement(docResult);
                Element headResult = XmlUtil.getElement(elementGR,"Head");
                String resCode = CommonUtils.XmlGetNodeContent(headResult,"FunCode");
                String resRemark = CommonUtils.XmlGetNodeContent(headResult,"Remark");

                log.setResponseBody(result);
                log.setResponseCode(resCode);
                log.setResponseResult(resRemark);
                ncServiceLogService.save(log);
                if("9000".equals(resCode)) {
                    //更新状态标记
                    UpdateWrapper<KDLCustomer> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("status",1).set("kdlts",DateUtils.now()).eq("id",id);
                    kdlCustomerMapper.update(new KDLCustomer(),updateWrapper);
                    return JsonResult.success(result);
                }else{
                    return JsonResult.error(resCode+":"+resRemark);
                }

            }
            catch (Exception ex)
            {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.success(result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitMaterial(Integer id) {
        try {
            ClassPathResource classPathResource = new ClassPathResource("kdl/" + "Material.xml");
            InputStream inputStream03 = classPathResource.getStream();
            Document document003= XmlUtil.readXML(inputStream03);
            Element elementG=XmlUtil.getRootElement(document003);
            Element Head = XmlUtil.getElement(elementG,"Head");
            Element elementD = XmlUtil.getElement(Head,"Details");
            Element Detail = XmlUtil.getElement(elementD,"Detail");

            KDLMaterial entity = kdlMaterialMapper.selectById(id);
            if(StringUtils.isNull(entity))
            {
                return JsonResult.error("无效的id:"+id.toString());
            }
            //判断封存状态
            if("Y".equals(entity.getFcbz())){
                return JsonResult.error("物料已封存，不能上传:"+entity.getMaterialdes()+"("+entity.getMaterialcode()+")");
            }
            //初始化提交报文
//            CommonUtils.XmlSetNodeContent(Head,"OrderType",entity.getOrdertype());
            CommonUtils.XmlSetNodeContent(Head,"PrincipalID",CommonConfig.kdlCompanyId);
            String senddate = DateUtil.format(DateUtils.dateTime("yyyy-MM-dd",entity.getSenddate()),"yyyyMMdd");
            CommonUtils.XmlSetNodeContent(Head,"SendDate",senddate);

            CommonUtils.XmlSetNodeContent(Head,"MaterialCode",entity.getMaterialcode());
            CommonUtils.XmlSetNodeContent(Head,"MaterialType",entity.getMaterialtype());
            CommonUtils.XmlSetNodeContent(Head,"MaterialDes",entity.getMaterialdes());
            CommonUtils.XmlSetNodeContent(Head,"MaterialGroup",entity.getMaterialgroup());
            CommonUtils.XmlSetNodeContent(Head,"ProductGroup",entity.getProductgroup());
            CommonUtils.XmlSetNodeContent(Head,"LRegistNo",entity.getLregistno());
            CommonUtils.XmlSetNodeContent(Head,"LExpiredDate",entity.getLexpireddate());
            CommonUtils.XmlSetNodeContent(Head,"BasicUnit",entity.getBasicunit());
            CommonUtils.XmlSetNodeContent(Head,"SalesUnit",entity.getSalesunit());
            CommonUtils.XmlSetNodeContent(Head,"ProductionLicenseNumber",entity.getProductionlicensenumber());
            CommonUtils.XmlSetNodeContent(Head,"ProductionLicenseExpiredDate",entity.getProductionlicenseexpireddate());


            CommonUtils.XmlSetNodeContent(Head,"OriginalCountry",entity.getOriginalcountry());
            CommonUtils.XmlSetNodeContent(Head,"Transportationitemgroup",entity.getTransportationitemgroup());
            CommonUtils.XmlSetNodeContent(Head,"Batch",entity.getBatch());
            CommonUtils.XmlSetNodeContent(Head,"Category",entity.getCategory());
            CommonUtils.XmlSetNodeContent(Head,"PurchaseUnit",entity.getPurchaseunit());
            CommonUtils.XmlSetNodeContent(Head,"ManufacturerName",entity.getManufacturername());
            CommonUtils.XmlSetNodeContent(Head,"Temp",entity.getTemp());
            CommonUtils.XmlSetNodeContent(Head,"Storagecondition",entity.getStoragecondition());
            CommonUtils.XmlSetNodeContent(Head,"ComDescription",entity.getComdescription());
            CommonUtils.XmlSetNodeContent(Head,"MaterialSpec",entity.getMaterialspec());
            CommonUtils.XmlSetNodeContent(Head,"MaterialForm",entity.getMaterialform());
            CommonUtils.XmlSetNodeContent(Head,"PackageForm",entity.getPackageform());
            CommonUtils.XmlSetNodeContent(Head,"ProductGroupCode",entity.getProductgroupcode());
            CommonUtils.XmlSetNodeContent(Head,"GSPCategoryCode",entity.getGspcategorycode());
//            CommonUtils.XmlSetNodeContent(Head,"NweGSPCategoryCode",entity.getNwegspcategorycode());
            CommonUtils.XmlSetNodeContent(Head,"Ecode",entity.getEcode());
            CommonUtils.XmlSetNodeContent(Head,"MedicineCode",entity.getMedicinecode());
            CommonUtils.XmlSetNodeContent(Head,"IMPLOC",entity.getImploc());
            CommonUtils.XmlSetNodeContent(Head,"Caution",entity.getCaution());
            CommonUtils.XmlSetNodeContent(Head,"PRFRQ",entity.getPrfrq());
            String approvedDate = DateUtil.format(DateUtils.dateTime("yyyy-MM-dd",entity.getRegistrationapproveddate()),"yyyyMMdd");

            CommonUtils.XmlSetNodeContent(Head,"RegistrationApprovedDate",approvedDate);

            CommonUtils.XmlSetNodeContent(Head,"PRFRQ",entity.getPrfrq());
            CommonUtils.XmlSetNodeContent(Head,"Humidityconditions",entity.getHumidityconditions());
            CommonUtils.XmlSetNodeContent(Head,"RegistrationFilingapplicantname",entity.getRegistrationfilingapplicantname());
            CommonUtils.XmlSetNodeContent(Head,"Commissionedmanufacturername",entity.getCommissionedmanufacturername());
            CommonUtils.XmlSetNodeContent(Head,"YZXPJ",entity.getYzxpj());
            CommonUtils.XmlSetNodeContent(Head,"Cstoragecon",entity.getCstoragecon());

            CommonUtils.XmlSetNodeContent(Detail,"ZXMEINH",entity.getZxmeinh());
            CommonUtils.XmlSetNodeContent(Detail,"UMREZ",String.valueOf(entity.getUmrez()));
            CommonUtils.XmlSetNodeContent(Detail,"Length",entity.getLength());
            CommonUtils.XmlSetNodeContent(Detail,"Width",entity.getWidth());
            CommonUtils.XmlSetNodeContent(Detail,"Height",entity.getHeight());


            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = XmlUtil.toStr(document003);
            log.setSubmitNo(entity.getMaterialcode());

            log.setRequestBody(body);
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox?SHYPConstants.KDL_MATERIAL_URL_SUFFIX_TEST:SHYPConstants.KDL_MATERIAL_URL_SUFFIX,"",null,body,CommonConfig.kdlSandbox);
                Document docResult= XmlUtil.readXML(result);
                Element elementGR=XmlUtil.getRootElement(docResult);
                Element headResult = XmlUtil.getElement(elementGR,"Head");
                String resCode = CommonUtils.XmlGetNodeContent(headResult,"FunCode");
                String resRemark = CommonUtils.XmlGetNodeContent(headResult,"Remark");

                log.setResponseBody(result);
                log.setResponseCode(resCode);
                log.setResponseResult(resRemark);
                ncServiceLogService.save(log);
                if("9000".equals(resCode)) {
                    //更新状态标记
                    UpdateWrapper<KDLMaterial> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("status",1).set("kdlts",DateUtils.now()).eq("id",id);
                    kdlMaterialMapper.update(new KDLMaterial(),updateWrapper);
                    return JsonResult.success(result);
                }else{
                    return JsonResult.error(resCode+":"+resRemark);
                }

            }
            catch (Exception ex)
            {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result)?ex.getMessage():result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncMaterial() {
        //获取最新NCTS
        try {
            String ncts = kdlMaterialMapper.GetMaxNCTS();
            List<KDLMaterial> customerList = kdlMaterialMapper.GetNCMaterialList(ncts);
            KDLMaterial customerLocal;
            Map<String, Object> param = new HashMap<>();
            for (KDLMaterial entity : customerList) {
                entity.setPrincipalid(CommonConfig.kdlCompanyId);
                entity.setOrdertype("ZMAU");
                entity.setSenddate(DateUtils.getDate());
                entity.setTs(DateUtils.now());
                param.put("materialcode", entity.getMaterialcode());
                List<KDLMaterial> list = kdlMaterialMapper.selectByMap(param);
                KDLMaterialLog entityLog = new KDLMaterialLog();

                if (list.size() > 0) {
                    customerLocal = list.get(0);
                    //判断是否修改了相关字段
                    //药厂客户编码、客户名称、客户地址、国家、地区、运输区域、行业、城市代码出现
                    String remark = isMaterialDataUpdated(entity, customerLocal);
                    if (!StringUtils.isEmpty(remark)) {
                        entity.setStatus(0);
                        entity.setId(customerLocal.getId());
                        BeanUtils.copyProperties(entity, entityLog);
                        entityLog.setRemark(remark);
                        kdlMaterialLogMapper.insert(entityLog);
                        kdlMaterialMapper.updateById(entity);
                    }

                } else {
                    kdlMaterialMapper.insert(entity);
                    BeanUtils.copyProperties(entity, entityLog);
                    kdlMaterialLogMapper.insert(entityLog);

                }
            }
            return JsonResult.success();
        }catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public String getMasterDataMaxSyncTime(String mastertype) {
        return kdlMaraMapper.GetMaxSyncTime(mastertype);
    }

    /**
     * 获取康德乐主数据审批结果
     * @param query
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncMasterDataResult(KdlMaraQuery query) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + CommonConfig.kdlCompanyId + "</PrincipalID>");
            sb.append("<DocType>MARA</DocType>");
            sb.append("<MasterType>" + query.getMastertype() + "</MasterType>");
            sb.append("<StartTime>" + query.getStarttime() + "</StartTime>");
            sb.append("<EndTime>" + query.getEndtime() + "</EndTime>");
            sb.append("</Head>");
            sb.append("</CAH3PL>");
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = sb.toString();
            log.setSubmitNo(query.getPrincipalid()+"_"+query.getDoctype());

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox?SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST: SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                //result = "<?xml version=\"1.0\" encoding=\"utf-8\"?><CAH3PL><Head><FunCode>9000</FunCode><Remark>读取数据成功</Remark><DocType>GM</DocType></Head><Details><Detail><OrderNo>4911568514</OrderNo><PrincipalOrderNo/><DOCNo>0000000063877638</DOCNo><Ordertype>311</Ordertype><SN>0001</SN><ItemNo>0119020401</ItemNo><BatchNo>0006403221</BatchNo><QTY>5000.000</QTY><Unit>EA</Unit><FromLocation>1012</FromLocation><ToLocation>1001</ToLocation><Plant>T150</Plant><Date>20240130</Date><GmName>吕 天成</GmName><VendorBatch>230132</VendorBatch><BoxFlag>ZX</BoxFlag><BoxNo/></Detail></Details></CAH3PL>";
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                //for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    //if(elementG.getChildNodes().item(j).getNodeType()!= Node.ELEMENT_NODE) {
                    //    continue;
                    //}
                    //Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementG, "Head");
                    Element detailResult = XmlUtil.getElement(elementG, "Details");
//                    String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
//                    String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                    String resCode = "9000";
                    String resRemark = "";
                    log.setResponseBody(result);
                    log.setResponseCode(resCode);
                    log.setResponseResult(resRemark);
                    ncServiceLogService.save(log);
                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存
                        KdlMara kdlGM = new KdlMara();
                        //遍历明细Details
                        Element detail = null;
                        Map<String,Object> param = new HashMap<>();
                        String syncTime = DateUtil.now();
                        for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            if(detailResult.getChildNodes().item(i).getNodeType()!= Node.ELEMENT_NODE) {
                                continue;
                            }
                            detail = (Element) detailResult.getChildNodes().item(i);
                            kdlGM.setMasterdatano(CommonUtils.XmlGetNodeContent(detail, "MasterdataNo"));
                            kdlGM.setKdlmasterno(CommonUtils.XmlGetNodeContent(detail, "KDLMasterNo"));
                            kdlGM.setResult(CommonUtils.XmlGetNodeContent(detail, "Result"));
                            kdlGM.setMastertype(query.getMastertype());
                            kdlGM.setApprover(CommonUtils.XmlGetNodeContent(detail, "Approver"));
                            kdlGM.setApprovaldate(CommonUtils.XmlGetNodeContent(detail, "Approvaldate"));
                            kdlGM.setSyncTime(CommonUtils.XmlGetNodeContent(detail, "Time"));
                            param.put("kdlmasterno",kdlGM.getKdlmasterno());
                            if(kdlMaraMapper.selectByMap(param).size()==0) {
                                kdlMaraMapper.insert(kdlGM);
                            }
                        }
                        //return JsonResult.success(result);
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                //}
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncCoaFile() {
        //下载药检报告
        boolean downSuccess = false;
        //连接sftp服务器
        ftpUtil.connect("sftp");
        //获取服务器目录下的文件列表
        List<String> coaFiles = ftpUtil.listFiles(CommonConfig.kdlSftpCOAPath);
        if(coaFiles==null){
            return JsonResult.error("连接Sftp服务器失败,请检查网络及sftp连接参数设置");
        }

        log.info(String.format("开始下载药检报告,获取到%d个待下载报告....", coaFiles.size()));
        NcTaskLog taskLog = new NcTaskLog();
        taskLog.setTaskType("下载药检报告");
        taskLog.setBillCount(coaFiles.size());
        taskLog.setStartTime(DateUtils.now());
        String billno = "";

        KdlCoa entity = null;
        KdlMara mara = null;
        List<KdlMara> listMara = null;
        Map<String,Object> param = new HashMap<>();
        for (String coaFile : coaFiles) {
            downSuccess = ftpUtil.downloadFile(CommonConfig.kdlSftpCOAPath, coaFile, CommonConfig.coaAttachFilePath);
            if(downSuccess) {
                entity = new KdlCoa();
                String[] list = coaFile.split("_");
                if (coaFile.contains("-")) {
                    list = coaFile.split("-");
                }
                param.clear();
                param.put("kdlmasterno", list[0]);
                listMara = kdlMaraMapper.selectByMap(param);
                if (listMara.size() > 0) {
                    mara = kdlMaraMapper.selectByMap(param).get(0);
                    entity.setMasterdatano(mara.getMasterdatano());
                }
                if (list.length >= 2) {
                    entity.setKdlmasterno(list[0]);
                    entity.setVendorbatch(list[1]);
                    entity.setFilename(coaFile);
                    entity.setStatus("正常");
                } else {
                    entity.setFilename(coaFile);
                    entity.setStatus("解析异常");
                }
                param.clear();
                param.put("filename",coaFile);
                if(kdlCoaMapper.selectByMap(param).size()>0){
                    ftpUtil.deleteFile(CommonConfig.kdlSftpCOAPath, coaFile);
                }else {
                    if (kdlCoaMapper.insert(entity) > 0) {
                        ftpUtil.deleteFile(CommonConfig.kdlSftpCOAPath, coaFile);
                    }
                }
            }else {
                log.info("下载ftp文件失败：" + CommonConfig.kdlSftpCOAPath + "/" + coaFile);
            }
        }
        ftpUtil.disconnect();
        taskLog.setBillNo(billno);
        taskLog.setEndTime(DateUtils.now());
        DynamicDataSource.setDataSource(DataSourceType.MASTER.getName());
        iNcTaskLogService.save(taskLog);
        DynamicDataSource.setDataSource(DataSourceType.SINESYS.getName());

        return JsonResult.success();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getMaraList(BaseQuery query) {
        KdlMaraQuery ncQuery = (KdlMaraQuery)query;
        IPage<KdlMara> page = new Page<>(ncQuery.getPage(), ncQuery.getLimit());
        IPage<KdlMara> pageData = kdlMaraMapper.getMaraList(page, ncQuery);

        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getCoaList(BaseQuery query) {
        KdlCoaQuery ncQuery = (KdlCoaQuery)query;
        IPage<KdlCoa> page = new Page<>(ncQuery.getPage(), ncQuery.getLimit());
        IPage<KdlCoa> pageData = kdlCoaMapper.getCoaList(page, ncQuery);

        return JsonResult.success(pageData);
    }


    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public String getPurchaseweMaxSyncTime() {
        return kdlPurchaseweMapper.GetMaxSyncTime();
    }

    /**
     * 获取康德乐采购收货
     * @param query
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncPurchasewe(KdlPurchaseweQuery query) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + CommonConfig.kdlCompanyId + "</PrincipalID>");
            sb.append("<DocType>WE</DocType>");
            sb.append("<StartTime>" + query.getStarttime() + "</StartTime>");
            sb.append("<EndTime>" + query.getEndtime() + "</EndTime>");
            sb.append("</Head>");
            sb.append("</CAH3PL>");
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = sb.toString();
            log.setSubmitNo(query.getPrincipalid()+"_WE");

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox?SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST: SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementGR, "Head");
                    Element detailResult = XmlUtil.getElement(elementGR, "Details");
                    String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                    String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                    log.setResponseBody(result);
                    log.setResponseCode(resCode);
                    log.setResponseResult(resRemark);
                    ncServiceLogService.save(log);
                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存
                        KdlPurchasewe purchasein = new KdlPurchasewe();
                        KdlPurchaseweB purchaseinB = new KdlPurchaseweB();
                        purchasein.setPrincipalid(CommonUtils.XmlGetNodeContent(headResult, "PrincipalID"));
                        purchasein.setPrincipalname(CommonUtils.XmlGetNodeContent(headResult, "PrincipalName"));
                        purchasein.setVendorpo(CommonUtils.XmlGetNodeContent(headResult, "VendorPO"));
                        purchasein.setDoctype(CommonUtils.XmlGetNodeContent(headResult, "DocType"));
                        String grdate = CommonUtils.XmlGetNodeContent(headResult, "GRDate");
                        purchasein.setGrdate(grdate);
                        purchasein.setCahdocno(CommonUtils.XmlGetNodeContent(headResult, "CAHDocNo"));
                        //根据供应商名称查询供应商代码
                        Map<String,Object> param = new HashMap<>();
                        param.put("suppliername",CommonUtils.XmlGetNodeContent(headResult, "VendorName"));
                        try {
                            KDLSupplier supplier = kdlSupplierMapper.selectByMap(param).get(0);
                            purchasein.setVendorcode(supplier.getSuppliercode());
                        }catch(Exception ex){
                            ex.printStackTrace();
                            purchasein.setVendorcode("");
                        }
                        purchasein.setCompanycode(CommonUtils.XmlGetNodeContent(headResult, "CompanyCode"));
                        purchasein.setGrid(CommonUtils.XmlGetNodeContent(headResult, "GRID"));
                        purchasein.setGridname(CommonUtils.XmlGetNodeContent(headResult, "GRIDName"));
                        List<KdlPurchasewe> list = kdlPurchaseweMapper.selectList(new QueryWrapper<KdlPurchasewe>().eq("vendorpo", purchasein.getVendorpo()));

                        if (list.size() == 0) {
                            kdlPurchaseweMapper.insert(purchasein);
                        } else {
                            purchasein.setUpdateTime(DateUtils.now());
                            purchasein.setId(list.get(0).getId());
                            kdlPurchaseweMapper.updateById(purchasein);
                        }
                        //遍历明细Details
                        Element detail = null;
                        for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            detail = (Element) detailResult.getChildNodes().item(i);
                            purchaseinB.setPid(purchasein.getId());
                            purchaseinB.setCahlineno(CommonUtils.XmlGetNodeContent(detail, "LineNo"));
                            purchaseinB.setMaterialcode(CommonUtils.XmlGetNodeContent(detail, "MaterialCode"));
                            purchaseinB.setCahmaterialcode(CommonUtils.XmlGetNodeContent(detail, "CAHMaterialCode"));
                            purchaseinB.setMaterialdes(CommonUtils.XmlGetNodeContent(detail, "MaterialDes"));
                            purchaseinB.setComdescription(CommonUtils.XmlGetNodeContent(detail, "ComDescription"));
                            purchaseinB.setMaterialspec(CommonUtils.XmlGetNodeContent(detail, "MaterialSpec"));
                            purchaseinB.setMaterialform(CommonUtils.XmlGetNodeContent(detail, "MaterialForm"));
                            purchaseinB.setRegistno(CommonUtils.XmlGetNodeContent(detail, "RegistNo"));
                            purchaseinB.setVendorrecplant(CommonUtils.XmlGetNodeContent(detail, "VendorRecPlant"));
                            purchaseinB.setCahrecplant(CommonUtils.XmlGetNodeContent(detail, "CAHRecPlant"));
                            purchaseinB.setGrquantity(new BigDecimal(CommonUtils.XmlGetNodeContent(detail, "GRQuantity", 0)));
                            purchaseinB.setGrfinish(CommonUtils.XmlGetNodeContent(detail, "GRFinish"));
                            purchaseinB.setUom(CommonUtils.XmlGetNodeContent(detail, "UOM"));
                            purchaseinB.setVendorbatch(CommonUtils.XmlGetNodeContent(detail, "VendorBatch"));
                            purchaseinB.setSapbatch(CommonUtils.XmlGetNodeContent(detail, "SAPbatch"));
                            purchaseinB.setSerialno(CommonUtils.XmlGetNodeContent(detail, "SerialNo"));
                            purchaseinB.setExpireddate(CommonUtils.XmlGetNodeContent(detail, "ExpiredDate"));
                            purchaseinB.setManufacturedate(CommonUtils.XmlGetNodeContent(detail, "ManufactureDate"));
                            purchaseinB.setManufacturername(CommonUtils.XmlGetNodeContent(detail, "ManufacturerName"));
                            purchaseinB.setSubmaufacturername(CommonUtils.XmlGetNodeContent(detail, "SubMaufacturerName"));
                            purchaseinB.setGrconculsion(CommonUtils.XmlGetNodeContent(detail, "GRConculsion"));
                            purchaseinB.setSterilizationbatch(CommonUtils.XmlGetNodeContent(detail, "SterilizationBatch"));
                            purchaseinB.setCarrier(CommonUtils.XmlGetNodeContent(detail, "Carrier"));
                            purchaseinB.setCarriermethod(CommonUtils.XmlGetNodeContent(detail, "CarrierMethod"));
                            purchaseinB.setTransitdate(CommonUtils.XmlGetNodeContent(detail, "TransitDate"));
                            purchaseinB.setTransittime(CommonUtils.XmlGetNodeContent(detail, "TransitTime"));
                            purchaseinB.setArrivaltemperature(CommonUtils.XmlGetNodeContent(detail, "ArrivalTemperature"));
                            purchaseinB.setTransitmethod(CommonUtils.XmlGetNodeContent(detail, "TransitMethod"));
                            purchaseinB.setDespatchtime(CommonUtils.XmlGetNodeContent(detail, "DespatchTime"));
                            purchaseinB.setMethodoftemperature(CommonUtils.XmlGetNodeContent(detail, "MethodofTemperature"));
                            purchaseinB.setStockarrivetime(CommonUtils.XmlGetNodeContent(detail, "StockArriveTime"));
                            purchaseinB.setPlaceofdelivery(CommonUtils.XmlGetNodeContent(detail, "PlaceofDelivery"));
                            purchaseinB.setTemperatureofstock(CommonUtils.XmlGetNodeContent(detail, "TemperatureofStock"));
                            purchaseinB.setInventorypacking(CommonUtils.XmlGetNodeContent(detail, "InventoryPacking"));
                            purchaseinB.setWofdareport(CommonUtils.XmlGetNodeContent(detail, "WOFDAReport"));
                            purchaseinB.setWodeliverynote(CommonUtils.XmlGetNodeContent(detail, "WODeliveryNote"));
                            purchaseinB.setDeliverier(CommonUtils.XmlGetNodeContent(detail, "Deliverier"));
                            purchaseinB.setTwoinvoice(CommonUtils.XmlGetNodeContent(detail, "TwoInvoice"));

                            purchaseinB.setSyncTime(CommonUtils.XmlGetNodeContent(detail, "Time"));


                            List<KdlPurchaseweB> list1 = kdlPurchaseweBMapper.selectList(new QueryWrapper<KdlPurchaseweB>().eq("cahlineno", purchaseinB.getCahlineno()).eq("sapbatch",purchaseinB.getSapbatch()));
                            if (list1.size() == 0) {
                                kdlPurchaseweBMapper.insert(purchaseinB);
                            } else {
                                purchaseinB.setId(list1.get(0).getId());
                                purchaseinB.setUpdateTime(DateUtils.now());
                                kdlPurchaseweBMapper.updateById(purchaseinB);
                            }
                        }

                        //return JsonResult.success(result);
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                }
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(ex.getMessage()) ? "" : ex.getMessage());

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }    }

    /**
     * 获取康德乐实时库存
     * @param query
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncInventory(KdlInventoryQuery query) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + CommonConfig.kdlCompanyId + "</PrincipalID>");
            sb.append("<DocType>Inventory</DocType>");
            sb.append("<Plant>" + query.getPlant() + "</Plant>");
            sb.append("</Head>");
            sb.append("<Details>");
            sb.append("<Detail>");
            sb.append("<Material>"+query.getMaterial()+"</Material>");
            sb.append("<VenderBatch>"+query.getVendorbatch()+"</VenderBatch>");
            sb.append("</Detail>");
            sb.append("</Details>");
            sb.append("</CAH3PL>");
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = sb.toString();
            log.setSubmitNo(query.getPrincipalid()+"_"+query.getDoctype());

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox?SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST: SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                //result = "<?xml version=\"1.0\" encoding=\"utf-8\"?><CAH3PL><Head><FunCode>9000</FunCode><Remark>读取数据成功</Remark><DocType>GM</DocType></Head><Details><Detail><OrderNo>4911568514</OrderNo><PrincipalOrderNo/><DOCNo>0000000063877638</DOCNo><Ordertype>311</Ordertype><SN>0001</SN><ItemNo>0119020401</ItemNo><BatchNo>0006403221</BatchNo><QTY>5000.000</QTY><Unit>EA</Unit><FromLocation>1012</FromLocation><ToLocation>1001</ToLocation><Plant>T150</Plant><Date>20240130</Date><GmName>吕 天成</GmName><VendorBatch>230132</VendorBatch><BoxFlag>ZX</BoxFlag><BoxNo/></Detail></Details></CAH3PL>";
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementGR, "Head");
                    Element detailResult = XmlUtil.getElement(elementGR, "Details");
                    String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                    String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                    log.setResponseBody(result);
                    log.setResponseCode(resCode);
                    log.setResponseResult(resRemark);
                    ncServiceLogService.save(log);
                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存
                        KdlInventory kdlGM = new KdlInventory();
                        //遍历明细Details
                        Element detail = null;
                        String syncTime = DateUtil.now();
                        for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            detail = (Element) detailResult.getChildNodes().item(i);
                            kdlGM.setCahmaterialcode(CommonUtils.XmlGetNodeContent(detail, "CAHMaterialCode"));
                            kdlGM.setMaterialcode(CommonUtils.XmlGetNodeContent(detail, "MaterialCode"));
                            kdlGM.setMaterialdes(CommonUtils.XmlGetNodeContent(detail, "MaterialDes"));
                            kdlGM.setPrincipalname(CommonUtils.XmlGetNodeContent(detail, "PrincipalName"));
                            kdlGM.setPrincipalid(query.getPrincipalid());
                            kdlGM.setVendorbatch(CommonUtils.XmlGetNodeContent(detail, "VendorBatch"));
                            kdlGM.setBatch(CommonUtils.XmlGetNodeContent(detail, "BATCH"));
                            kdlGM.setManufacturedate(CommonUtils.XmlGetNodeContent(detail, "ManufactureDate"));
                            kdlGM.setExpireddate(CommonUtils.XmlGetNodeContent(detail, "ExpiredDate"));
                            kdlGM.setQty(new BigDecimal(CommonUtils.XmlGetNodeContent(detail, "Qty", 0)));
                            kdlGM.setUom(CommonUtils.XmlGetNodeContent(detail, "UOM"));
                            kdlGM.setUuqty(new BigDecimal(CommonUtils.XmlGetNodeContent(detail, "UUQty", 0)));
                            kdlGM.setUiqty(new BigDecimal(CommonUtils.XmlGetNodeContent(detail, "QIQty", 0)));
                            kdlGM.setBlockqty(new BigDecimal(CommonUtils.XmlGetNodeContent(detail, "BlockQty", 0)));
                            kdlGM.setLocation(CommonUtils.XmlGetNodeContent(detail, "Location"));
                            kdlGM.setPlant(CommonUtils.XmlGetNodeContent(detail, "Plant"));
                            kdlGM.setStoragetime(CommonUtils.XmlGetNodeContent(detail, "Storagetime"));
                            kdlGM.setBoxflag(CommonUtils.XmlGetNodeContent(detail, "BoxFlag"));
                            kdlGM.setBoxno(CommonUtils.XmlGetNodeContent(detail, "BoxNo"));
                            kdlGM.setReturnTime(CommonUtils.XmlGetNodeContent(detail, "ReturnTime"));
                            kdlGM.setStorageLocation(CommonUtils.XmlGetNodeContent(detail, "Storagelocation"));
                            kdlGM.setStorageType(StringUtils.trim(CommonUtils.XmlGetNodeContent(detail, "Storagetype")).replaceAll(" ", ""));
                            kdlGM.setSyncTime(syncTime);

                            kdlInventoryMapper.insert(kdlGM);
                        }
                        //删除之前同步的库存数据
                        kdlInventoryMapper.delete(new UpdateWrapper<KdlInventory>().ne("sync_time",syncTime));

                        //return JsonResult.success(result);
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                }
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncInventoryDay(KdlInventoryQuery query) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + query.getPrincipalid() + "</PrincipalID>");
            sb.append("<DocType>Inventory</DocType>");
            sb.append("<Plant>" + query.getPlant() + "</Plant>");
            sb.append("</Head>");
            sb.append("<Details>");
            sb.append("<Detail>");
            sb.append("<Material>"+query.getMaterial()+"</Material>");
            sb.append("<VenderBatch>"+query.getVendorbatch()+"</VenderBatch>");
            sb.append("</Detail>");
            sb.append("</Details>");
            sb.append("</CAH3PL>");
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = sb.toString();
            log.setSubmitNo(query.getPrincipalid()+"_"+query.getDoctype());

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox?SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST: SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                //result = "<?xml version=\"1.0\" encoding=\"utf-8\"?><CAH3PL><Head><FunCode>9000</FunCode><Remark>读取数据成功</Remark><DocType>GM</DocType></Head><Details><Detail><OrderNo>4911568514</OrderNo><PrincipalOrderNo/><DOCNo>0000000063877638</DOCNo><Ordertype>311</Ordertype><SN>0001</SN><ItemNo>0119020401</ItemNo><BatchNo>0006403221</BatchNo><QTY>5000.000</QTY><Unit>EA</Unit><FromLocation>1012</FromLocation><ToLocation>1001</ToLocation><Plant>T150</Plant><Date>20240130</Date><GmName>吕 天成</GmName><VendorBatch>230132</VendorBatch><BoxFlag>ZX</BoxFlag><BoxNo/></Detail></Details></CAH3PL>";
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementGR, "Head");
                    Element detailResult = XmlUtil.getElement(elementGR, "Details");
                    String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                    String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                    log.setResponseBody(result);
                    log.setResponseCode(resCode);
                    log.setResponseResult(resRemark);
                    ncServiceLogService.save(log);
                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存
                        KdlInventoryDay kdlGM = new KdlInventoryDay();
                        //遍历明细Details
                        Element detail = null;
                        String syncTime = DateUtil.now();
                        for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            detail = (Element) detailResult.getChildNodes().item(i);
                            kdlGM.setCahmaterialcode(CommonUtils.XmlGetNodeContent(detail, "CAHMaterialCode"));
                            kdlGM.setMaterialcode(CommonUtils.XmlGetNodeContent(detail, "MaterialCode"));
                            kdlGM.setMaterialdes(CommonUtils.XmlGetNodeContent(detail, "MaterialDes"));
                            kdlGM.setPrincipalname(CommonUtils.XmlGetNodeContent(detail, "PrincipalName"));
                            kdlGM.setPrincipalid(query.getPrincipalid());
                            kdlGM.setVendorbatch(CommonUtils.XmlGetNodeContent(detail, "VendorBatch"));
                            kdlGM.setBatch(CommonUtils.XmlGetNodeContent(detail, "BATCH"));
                            kdlGM.setManufacturedate(CommonUtils.XmlGetNodeContent(detail, "ManufactureDate"));
                            kdlGM.setExpireddate(CommonUtils.XmlGetNodeContent(detail, "ExpiredDate"));
                            kdlGM.setQty(new BigDecimal(CommonUtils.XmlGetNodeContent(detail, "Qty", 0)));
                            kdlGM.setUom(CommonUtils.XmlGetNodeContent(detail, "UOM"));
                            kdlGM.setUuqty(new BigDecimal(CommonUtils.XmlGetNodeContent(detail, "UUQty", 0)));
                            kdlGM.setUiqty(new BigDecimal(CommonUtils.XmlGetNodeContent(detail, "QIQty", 0)));
                            kdlGM.setBlockqty(new BigDecimal(CommonUtils.XmlGetNodeContent(detail, "BlockQty", 0)));
                            kdlGM.setLocation(CommonUtils.XmlGetNodeContent(detail, "Location"));
                            kdlGM.setPlant(CommonUtils.XmlGetNodeContent(detail, "Plant"));
                            kdlGM.setStoragetime(CommonUtils.XmlGetNodeContent(detail, "Storagetime"));
                            kdlGM.setBoxflag(CommonUtils.XmlGetNodeContent(detail, "BoxFlag"));
                            kdlGM.setBoxno(CommonUtils.XmlGetNodeContent(detail, "BoxNo"));
                            kdlGM.setReturnTime(CommonUtils.XmlGetNodeContent(detail, "ReturnTime"));
                            kdlGM.setStorageLocation(CommonUtils.XmlGetNodeContent(detail, "Storagelocation"));
                            kdlGM.setStorageType(CommonUtils.XmlGetNodeContent(detail, "Storagetype"));

                            kdlGM.setSyncTime(syncTime);
                            kdlGM.setSyncDay(DateUtils.getDate());

                            kdlInventoryDayMapper.insert(kdlGM);
                        }
                        //删除之前同步的库存数据
                        kdlInventoryDayMapper.delete(new UpdateWrapper<KdlInventoryDay>().ne("sync_time",syncTime).eq("sync_day",DateUtils.getDate()));

                        //return JsonResult.success(result);
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                }
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public String getQffMaxSyncTime() {
        return kdlQffFeedbackMapper.GetMaxSyncTime();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncQffFeedback(QffFeedbackQuery query) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + CommonConfig.kdlCompanyId + "</PrincipalID>");
            sb.append("<DocType>QFF</DocType>");
            sb.append("<StartTime>" + query.getStarttime() + "</StartTime>");
            sb.append("<EndTime>" + query.getEndtime() + "</EndTime>");
            sb.append("</Head>");
            sb.append("</CAH3PL>");
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = sb.toString();
            log.setSubmitNo(query.getPrincipalid()+"_"+query.getDoctype());

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox? SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST:SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                //result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><CAH3PL><Head><FunCode>9000</FunCode><Remark>读取数据成功</Remark><PrincipalID>111385</PrincipalID></Head><Details><Detail><QFFNo>000200067786</QFFNo><Inspectiontype/><Plant>T150</Plant><CAHMaterialCode>000000000030518554</CAHMaterialCode><BATCH>0006403219</BATCH><ItemNo>0118030301</ItemNo><VendorBatch>230130</VendorBatch><ManufactureDate>2023-05-15</ManufactureDate><ExpiredDate>2025-05-14</ExpiredDate><Result>外观破损</Result><Qty>0.000</Qty><Location/><OrderNo>1528CD2401</OrderNo><ERDAT>2024-02-18</ERDAT><BoxFlag>ZX</BoxFlag><BoxNo/></Detail></Details></CAH3PL>";
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                String companycode = "";
                //for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    //Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementG, "Head");
                    Element detailResult = XmlUtil.getElement(elementG, "Details");
                    Element attachResult = null;
                    String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                    String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                    log.setResponseBody(result);
                    log.setResponseCode(resCode);
                    log.setResponseResult(resRemark);
                    ncServiceLogService.save(log);
                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存
                        KdlQffFeedback qff = new KdlQffFeedback();
                        KdlQffAttach kdlQffAttach = new KdlQffAttach();
                        //遍历明细Details
                        Element detail = null;
                        Element attach = null;
                        String syncTime = DateUtil.now();
                        for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            detail = (Element) detailResult.getChildNodes().item(i);
                            attachResult = XmlUtil.getElement(detail, "AttachFiles");
                            qff.setQffno(CommonUtils.XmlGetNodeContent(detail, "QFFNo"));
                            qff.setInspectiontype(CommonUtils.XmlGetNodeContent(detail, "Inspectiontype"));
                            qff.setPlant(CommonUtils.XmlGetNodeContent(detail, "Plant"));
                            qff.setCahmaterialcode(CommonUtils.XmlGetNodeContent(detail, "CAHMaterialCode"));
                            qff.setBatch(CommonUtils.XmlGetNodeContent(detail, "BATCH"));
                            qff.setItemno(CommonUtils.XmlGetNodeContent(detail, "ItemNo"));
                            qff.setPrincipalid(query.getPrincipalid());
                            qff.setVendorbatch(CommonUtils.XmlGetNodeContent(detail, "VendorBatch"));
                            qff.setManufacturedate(CommonUtils.XmlGetNodeContent(detail, "ManufactureDate"));
                            qff.setExpireddate(CommonUtils.XmlGetNodeContent(detail, "ExpiredDate"));
                            qff.setQty(new BigDecimal(CommonUtils.XmlGetNodeContent(detail, "Qty", 0)));
                            qff.setResult(CommonUtils.XmlGetNodeContent(detail, "Result"));
                            qff.setLocation(CommonUtils.XmlGetNodeContent(detail, "Location"));
                            qff.setErdat(CommonUtils.XmlGetNodeContent(detail, "ERDAT"));
                            qff.setOrderno(CommonUtils.XmlGetNodeContent(detail, "OrderNo"));
                            qff.setBoxflag(CommonUtils.XmlGetNodeContent(detail, "BoxFlag"));
                            qff.setBoxno(CommonUtils.XmlGetNodeContent(detail, "BoxNo"));
                            companycode = StringUtils.trim(kdlQffFeedbackMapper.getCompanyCode(qff.getOrderno()));
                            qff.setCompanycode(companycode);

                            //qff.setSyncTime(syncTime);
                            Map<String,Object> param = new HashMap<>();
                            param.put("qffno",qff.getQffno());
                            List<KdlQffFeedback> list = kdlQffFeedbackMapper.selectByMap(param);
                            if(list.size()==0) {
                                qff.setPrincipalorderno(kdlQffFeedbackMapper.getPrincipalOrderNo());
                                qff.setStatus("待处理");
                                //插入oa qff
                                insertOaQff(qff);
                                DynamicDataSource.setDataSource(DataSourceType.SINESYS.getName());
                                kdlQffFeedbackMapper.insert(qff);
                            }else{
                                //已下发KDL的单据不做更新
                                if(!list.get(0).getStatus().equals("已反馈")) {
                                    qff.setStatus(list.get(0).getStatus());
                                    qff.setPrincipalorderno(list.get(0).getPrincipalorderno());
                                    qff.setUpdateTime(DateUtils.now());
                                    qff.setId(list.get(0).getId());
                                    kdlQffFeedbackMapper.updateById(qff);
                                }
                            }
                            //遍历处理附件信息
                            kdlQffAttachMapper.deleteByMap(param);
                            if(attachResult!=null && attachResult.getChildNodes().getLength()>0) {
                                for (int k = 0; k < attachResult.getChildNodes().getLength(); k++) {
                                    attach = (Element) attachResult.getChildNodes().item(k);
                                    kdlQffAttach.setQffno(qff.getQffno());
                                    kdlQffAttach.setAttachfile(CommonUtils.XmlGetNodeContent(attach, "AttachFile"));
                                    kdlQffAttachMapper.insert(kdlQffAttach);
                                }
                            }

                            }
                        //return JsonResult.success(result);
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                //}
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    /**
     * 发起批次号修改OA流程
     * @param qff
     */
    private void insertOaBatchChange(KdlQffFeedback qff) {
        try {
            FormtableMain12974 main12974 = new FormtableMain12974();
            main12974.setSqyw1(FormtableMain12974Constant.Sqyw1_9);
            main12974.setBt("批次号调整库存"+ qff.getOrderno());
            main12974.setSqr("wb003725");
            main12974.setSqrq(DateUtils.getDate());
            main12974.setSqnr("物料：" + qff.getItemno() + " 批号：" + qff.getVendorbatch() + " 数量：" + qff.getQty() + " 库位：" + qff.getLocation());
            main12974.setDjid(qff.getPrincipalorderno());
            main12974.setLy("供应链中台");
            main12974.setFj("/qff/" + qff.getQffno() + "/");
            //附件
            main12974.setFtriggerflag("1");
            main12974.setBz(qff.getResult());
            DynamicDataSource.setDataSource(DataSourceType.BIP.getName());
            List<FormtableMain12974> list = formtableMain12974Mapper.selectList(new QueryWrapper<FormtableMain12974>().eq("djid", qff.getPrincipalorderno()));
            if (CollectionUtils.isEmpty(list)) {
                formtableMain12974Mapper.insert(main12974);
            }
            DynamicDataSource.setDataSource(DataSourceType.SINESYS.getName());
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("insertOaQff error");
        }
    }

    private void insertOaQff(KdlQffFeedback qff) {
        try {
            FormtableMain12974 main12974 = new FormtableMain12974();
            main12974.setSqyw1(FormtableMain12974Constant.Sqyw1_0);
            main12974.setBt("kdl异常反馈"+ qff.getOrderno());
            main12974.setSqr("wb003725");
            main12974.setSqrq(DateUtils.getDate());
            KDLMaterial material = kdlMaterialMapper.getMaterialByCode(qff.getItemno());
            String materialName = material == null ? "" : material.getComdescription();
            main12974.setSqnr("药品名称：" + materialName + "物料：" + qff.getItemno() + " 批号：" + qff.getVendorbatch() + " 数量：" + qff.getQty() + " 库位：" + qff.getLocation()
                    + " 箱型：" + qff.getBoxflag()
            );
            main12974.setDjid(qff.getPrincipalorderno());
            main12974.setLy("供应链中台");
            main12974.setFj("/qff/" + qff.getQffno() + "/");
            //附件
            main12974.setFtriggerflag("1");
            main12974.setBz(qff.getResult());
            DynamicDataSource.setDataSource(DataSourceType.BIP.getName());
            List<FormtableMain12974> list = formtableMain12974Mapper.selectList(new QueryWrapper<FormtableMain12974>().eq("djid", qff.getPrincipalorderno()));
            if (CollectionUtils.isEmpty(list)) {
                formtableMain12974Mapper.insert(main12974);
            }
            DynamicDataSource.setDataSource(DataSourceType.SINESYS.getName());
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("insertOaQff error");
        }
    }


    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public String getTransReportMaxSyncTime() {
        return kdlTransReportMapper.GetMaxSyncTime();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncTransReport(QffFeedbackQuery query) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + CommonConfig.kdlCompanyId + "</PrincipalID>");
            sb.append("<OrderNo></OrderNo>");
            sb.append("<DocType>ZTRN</DocType>");
            sb.append("</Head>");
            sb.append("<Details>");
            sb.append("<Detail>");
            sb.append("<Material></Material>");
            sb.append("<BATCH></BATCH>");
            sb.append("<FROMDATE>" + query.getStarttime() + "</FROMDATE>");
            sb.append("<TODATE>" + query.getEndtime() + "</TODATE>");
            sb.append("<POINT></POINT>");
            sb.append("<DELIVERY></DELIVERY>");
            sb.append("</Detail>");
            sb.append("</Details>");
            sb.append("</CAH3PL>");
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = sb.toString();
            log.setSubmitNo(query.getPrincipalid()+"_"+query.getDoctype());

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox? SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST:SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                //result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><CAH3PL><Head><FunCode>9000</FunCode><Remark>读取数据成功</Remark><PrincipalID>111385</PrincipalID></Head><Details><Detail><QFFNo>000200067786</QFFNo><Inspectiontype/><Plant>T150</Plant><CAHMaterialCode>000000000030518554</CAHMaterialCode><BATCH>0006403219</BATCH><ItemNo>0118030301</ItemNo><VendorBatch>230130</VendorBatch><ManufactureDate>2023-05-15</ManufactureDate><ExpiredDate>2025-05-14</ExpiredDate><Result>外观破损</Result><Qty>0.000</Qty><Location/><OrderNo>1528CD2401</OrderNo><ERDAT>2024-02-18</ERDAT><BoxFlag>ZX</BoxFlag><BoxNo/></Detail></Details></CAH3PL>";
                Document docResult = XmlUtil.readXML(result);
                Map<String,Object> param = new HashMap<>();

                Element elementG = XmlUtil.getRootElement(docResult);
                for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementGR, "Head");
                    Element detailResult = XmlUtil.getElement(elementGR, "Details");
                    String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                    String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                    log.setResponseBody(result);
                    log.setResponseCode(resCode);
                    log.setResponseResult(resRemark);
                    ncServiceLogService.save(log);
                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存
                        KdlTransReport kdlGM = new KdlTransReport();
                        //遍历明细Details
                        Element detail = null;
                        String syncTime = DateUtil.now();
                        for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            detail = (Element) detailResult.getChildNodes().item(i);
                            kdlGM.setDispatch_date(CommonUtils.XmlGetNodeContent(detail, "DISPATCH_DATE"));
                            kdlGM.setConsignee(CommonUtils.XmlGetNodeContent(detail, "CONSIGNEE"));
                            kdlGM.setDelivery_address(CommonUtils.XmlGetNodeContent(detail, "DELIVERY_ADDRESS"));
                            kdlGM.setPacking_list_number(CommonUtils.XmlGetNodeContent(detail, "PACKING_LIST_NUMBER"));
                            kdlGM.setNo_of_parcel(CommonUtils.XmlGetNodeContent(detail, "NO_OF_PARCEL"));
                            kdlGM.setPlate_no(CommonUtils.XmlGetNodeContent(detail, "PLATE_NO"));
                            kdlGM.setPrincipalid(query.getPrincipalid());
                            kdlGM.setDelivery_person(CommonUtils.XmlGetNodeContent(detail, "DELIVERY_PERSON"));
                            kdlGM.setService_vendor(CommonUtils.XmlGetNodeContent(detail, "SERVICE_VENDOR"));
                            kdlGM.setService_code(CommonUtils.XmlGetNodeContent(detail, "SERVICE_CODE"));
                            kdlGM.setVsart(CommonUtils.XmlGetNodeContent(detail, "VSART"));
                            kdlGM.setBezei(CommonUtils.XmlGetNodeContent(detail, "BEZEI"));
                            kdlGM.setIssue_add(CommonUtils.XmlGetNodeContent(detail, "ISSUE_ADD"));
                            kdlGM.setDriver(CommonUtils.XmlGetNodeContent(detail, "DRIVER"));
                            kdlGM.setArrival_datetime(CommonUtils.XmlGetNodeContent(detail, "ARRIVAL_DATETIME"));
                            kdlGM.setMedicine_name(CommonUtils.XmlGetNodeContent(detail, "MEDICINE_NAME"));
                            kdlGM.setLicha(CommonUtils.XmlGetNodeContent(detail, "LICHA"));
                            kdlGM.setGoodsrec_person(CommonUtils.XmlGetNodeContent(detail, "GOODSREC_PERSON"));
                            kdlGM.setGoodsrec_department(CommonUtils.XmlGetNodeContent(detail, "GOODSREC_DEPARTMENT"));
                            kdlGM.setShpmnt_tool(CommonUtils.XmlGetNodeContent(detail, "SHPMNT_TOOL"));
                            kdlGM.setStart_shpmnt_datetime(CommonUtils.XmlGetNodeContent(detail, "START_SHPMNT_DATETIME"));
                            kdlGM.setArrival_temp(CommonUtils.XmlGetNodeContent(detail, "ARRIVAL_TEMP"));
                            kdlGM.setMatnr(CommonUtils.XmlGetNodeContent(detail, "MATNR"));
                            kdlGM.setZzprnpn(CommonUtils.XmlGetNodeContent(detail, "ZZPRNPN"));
                            kdlGM.setMaktx(CommonUtils.XmlGetNodeContent(detail, "MAKTX"));
                            kdlGM.setSpecs(CommonUtils.XmlGetNodeContent(detail, "SPECS"));
                            kdlGM.setLfimg(new BigDecimal(CommonUtils.XmlGetNodeContent(detail, "LFIMG", 0)));
                            kdlGM.setVrkme(CommonUtils.XmlGetNodeContent(detail, "VRKME"));
                            kdlGM.setRegistration_no(CommonUtils.XmlGetNodeContent(detail, "REGISTRATION_NO"));
                            kdlGM.setProduct_class(CommonUtils.XmlGetNodeContent(detail, "PRODUCT_CLASS"));
                            kdlGM.setGsp_class(CommonUtils.XmlGetNodeContent(detail, "GSP_CLASS"));
                            kdlGM.setWerks(CommonUtils.XmlGetNodeContent(detail, "WERKS"));
                            kdlGM.setClient_name(CommonUtils.XmlGetNodeContent(detail, "CLIENT_NAME"));
                            kdlGM.setZzvbeln_so(CommonUtils.XmlGetNodeContent(detail, "ZZVBELN_SO"));
                            kdlGM.setWaybillno(CommonUtils.XmlGetNodeContent(detail, "WAYBILLNO"));
                            kdlGM.setCompanycode(CommonUtils.XmlGetNodeContent(detail, "COMPANY_CODE"));
                            kdlGM.setSyncTime(syncTime);
                            kdlGM.setOperator1(CommonUtils.XmlGetNodeContent(detail, "OPERATOR"));
                            kdlGM.setConsignor1("");
                            kdlGM.setConsignor2("");
                            kdlGM.setOperator2("");
                            param.clear();
                            param.put("packing_list_number",kdlGM.getPacking_list_number());
                            param.put("zzprnpn",kdlGM.getZzprnpn());
                            param.put("licha",kdlGM.getLicha());

                            List<KdlTransReport> list1 = kdlTransReportMapper.selectByMap(param);
                            if(list1.size()>0){
                                kdlGM.setId(list1.get(0).getId());
                                kdlGM.setConsignor1(list1.get(0).getConsignor1());
                                kdlGM.setConsignor2(list1.get(0).getConsignor2());
                                //kdlGM.setOperator1(list1.get(0).getOperator1());
                                kdlGM.setOperator2(list1.get(0).getOperator2());
                                kdlGM.setUpdateTime(DateUtils.now());
                                kdlTransReportMapper.updateById(kdlGM);
                            }else {
                                kdlTransReportMapper.insert(kdlGM);
                            }

                        }
                        //return JsonResult.success(result);
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                }
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                //return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);
                return JsonResult.error(ex.getMessage());

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }


    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public String getMaintainReportMaxSyncTime() {
        return kdlMaintainReportMapper.GetMaxSyncTime();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncMaintainReport(QffFeedbackQuery query) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + CommonConfig.kdlCompanyId + "</PrincipalID>");
            sb.append("<DocType>INST</DocType>");
            sb.append("<FROMDATE>" + query.getStarttime() + "</FROMDATE>");
            sb.append("<TODATE>" + query.getEndtime() + "</TODATE>");
            sb.append("</Head>");
            sb.append("</CAH3PL>");
            String[] list = ShiroUtils.getOrgCode();
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = sb.toString();
            log.setSubmitNo(query.getPrincipalid()+"_"+query.getDoctype());

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox?SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST: SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                //result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><CAH3PL><Head><FunCode>9000</FunCode><Remark>读取数据成功</Remark><PrincipalID>111385</PrincipalID></Head><Details><Detail><QFFNo>000200067786</QFFNo><Inspectiontype/><Plant>T150</Plant><CAHMaterialCode>000000000030518554</CAHMaterialCode><BATCH>0006403219</BATCH><ItemNo>0118030301</ItemNo><VendorBatch>230130</VendorBatch><ManufactureDate>2023-05-15</ManufactureDate><ExpiredDate>2025-05-14</ExpiredDate><Result>外观破损</Result><Qty>0.000</Qty><Location/><OrderNo>1528CD2401</OrderNo><ERDAT>2024-02-18</ERDAT><BoxFlag>ZX</BoxFlag><BoxNo/></Detail></Details></CAH3PL>";
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                String resCode = CommonUtils.XmlGetNodeContent((Element) elementG.getChildNodes().item(0), "FunCode");
                String resRemark = CommonUtils.XmlGetNodeContent((Element) elementG.getChildNodes().item(0), "Remark");

                log.setResponseBody(result);
                log.setResponseCode(resCode);
                log.setResponseResult(resRemark);
                ncServiceLogService.save(log);
                for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementGR, "Head");
                    Element detailResult = XmlUtil.getElement(elementGR, "Details");
                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存
                        KdlMaintainReport kdlGM = new KdlMaintainReport();
                        //遍历明细Details
                        Element detail = null;
                        String syncTime = DateUtil.now();
                        //for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            //detail = (Element) detailResult.getChildNodes().item(i);
                            kdlGM.setInspectionlot(CommonUtils.XmlGetNodeContent(headResult, "InspectionLot"));
                            kdlGM.setCahmaterialcode(CommonUtils.XmlGetNodeContent(headResult, "CAHMaterialCode"));
                            kdlGM.setMaterialcode(CommonUtils.XmlGetNodeContent(headResult, "MaterialCode"));
                            kdlGM.setMaterialdes(CommonUtils.XmlGetNodeContent(headResult, "MaterialDes"));
                            kdlGM.setPrincipalname(CommonUtils.XmlGetNodeContent(headResult, "PrincipalName"));
                            kdlGM.setComdescription(CommonUtils.XmlGetNodeContent(headResult, "ComDescription"));
                            kdlGM.setPrincipalid(query.getPrincipalid());
                            kdlGM.setCommoditydes(CommonUtils.XmlGetNodeContent(headResult, "CommodityDes"));
                            kdlGM.setMaterialform(CommonUtils.XmlGetNodeContent(headResult, "MaterialForm"));
                            kdlGM.setMaterialformdes(CommonUtils.XmlGetNodeContent(headResult, "MaterialFormDes"));
                            kdlGM.setMaterialspec(CommonUtils.XmlGetNodeContent(headResult, "MaterialSpec"));
                            kdlGM.setManufacturername(CommonUtils.XmlGetNodeContent(headResult, "ManufacturerName"));
                            kdlGM.setVendorbatch(CommonUtils.XmlGetNodeContent(headResult, "VendorBatch"));
                            kdlGM.setBatch(CommonUtils.XmlGetNodeContent(headResult, "BATCH"));
                            kdlGM.setManufacturedate(CommonUtils.XmlGetNodeContent(headResult, "ManufactureDate"));
                            kdlGM.setExpireddate(CommonUtils.XmlGetNodeContent(headResult, "ExpiredDate"));
                            kdlGM.setRegistno(CommonUtils.XmlGetNodeContent(headResult, "RegistNo"));
                            kdlGM.setVname(CommonUtils.XmlGetNodeContent(headResult, "VNAME"));
                            kdlGM.setVdatum(CommonUtils.XmlGetNodeContent(headResult, "VDATUM"));
                            kdlGM.setLosmenge(new BigDecimal(CommonUtils.XmlGetNodeContent(headResult, "LOSMENGE", 0)));
                            kdlGM.setUom(CommonUtils.XmlGetNodeContent(headResult, "UOM"));
                            kdlGM.setUomdes(CommonUtils.XmlGetNodeContent(headResult, "UOMDes"));
                        kdlGM.setQty_accept(new BigDecimal(CommonUtils.XmlGetNodeContent(headResult, "QTY_ACCEPT", 0)));
                        kdlGM.setQty_reject(new BigDecimal(CommonUtils.XmlGetNodeContent(headResult, "QTY_REJECT", 0)));
                            kdlGM.setPlant(CommonUtils.XmlGetNodeContent(headResult, "Plant"));

                            kdlGM.setSyncTime(syncTime);
//                        if(ncOnhandMapper.getOrgcodeList(kdlGM.getMaterialcode(),kdlGM.getVendorbatch()).size()==1) {
//                            String companycode = ncOnhandMapper.getOrgcodeByInvcodeLotno(kdlGM.getMaterialcode(), kdlGM.getVendorbatch());
//                            kdlGM.setCompanycode(companycode);
//                        }
                            Map<String,Object> param = new HashMap<>();
                            param.put("InspectionLot",kdlGM.getInspectionlot());
                            List<KdlMaintainReport> list1 = kdlMaintainReportMapper.selectByMap(param);
                            if(list1.size()>0){
                                kdlGM.setId(list1.get(0).getId());
                                kdlGM.setUpdateTime(DateUtils.now());
                                kdlMaintainReportMapper.updateById(kdlGM);
                            }else {
                                kdlMaintainReportMapper.insert(kdlGM);
                            }
                        //}
                        //return JsonResult.success(result);
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                }
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public String getPODMaxSyncTime() {
        return kdlPODMapper.GetMaxSyncTime();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncPOD(RGRQuery query) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + CommonConfig.kdlCompanyId + "</PrincipalID>");
            sb.append("<DocType>POD</DocType>");
            sb.append("<StartTime>" + query.getStarttime() + "</StartTime>");
            sb.append("<EndTime>" + query.getEndtime() + "</EndTime>");
            sb.append("</Head>");
            sb.append("</CAH3PL>");
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = sb.toString();
            log.setSubmitNo(query.getPrincipalid()+"_"+query.getDoctype());

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox? SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST:SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                //result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><CAH3PL><Head><FunCode>9000</FunCode><Remark>读取数据成功</Remark><PrincipalID>111385</PrincipalID></Head><Details><Detail><QFFNo>000200067786</QFFNo><Inspectiontype/><Plant>T150</Plant><CAHMaterialCode>000000000030518554</CAHMaterialCode><BATCH>0006403219</BATCH><ItemNo>0118030301</ItemNo><VendorBatch>230130</VendorBatch><ManufactureDate>2023-05-15</ManufactureDate><ExpiredDate>2025-05-14</ExpiredDate><Result>外观破损</Result><Qty>0.000</Qty><Location/><OrderNo>1528CD2401</OrderNo><ERDAT>2024-02-18</ERDAT><BoxFlag>ZX</BoxFlag><BoxNo/></Detail></Details></CAH3PL>";
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementGR, "Head");
                    Element detailResult = XmlUtil.getElement(elementGR, "Details");
                    String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                    String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                    log.setResponseBody(result);
                    log.setResponseCode(resCode);
                    log.setResponseResult(resRemark);
                    ncServiceLogService.save(log);
                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存
                        KdlPOD kdlGM = new KdlPOD();
                        //遍历明细Details
                        Element detail = null;
                        String syncTime = DateUtil.now();
                        Map<String,Object> param = new HashMap<>();
                        List<KdlPOD> rgrList = null;
                        for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            param.clear();
                            detail = (Element) detailResult.getChildNodes().item(i);
                            kdlGM.setPrincipalid(query.getPrincipalid());
                            kdlGM.setDeliverynumber(CommonUtils.XmlGetNodeContent(detail, "DeliveryNumber"));
                            kdlGM.setVendernumber(CommonUtils.XmlGetNodeContent(detail, "VenderNumber"));
                            kdlGM.setPoddate(CommonUtils.XmlGetNodeContent(detail, "PODDate"));
                            kdlGM.setPodtime(CommonUtils.XmlGetNodeContent(detail, "PODTime"));
                            kdlGM.setOrderno(CommonUtils.XmlGetNodeContent(headResult, "OrderNo"));
                            kdlGM.setOrdertype(CommonUtils.XmlGetNodeContent(headResult, "OrderType"));

                            kdlGM.setSyncTime(syncTime);
                            param.put("deliverynumber",kdlGM.getDeliverynumber());
                            rgrList = kdlPODMapper.selectByMap(param);
                            if(rgrList.size()>0){
                                kdlGM.setUpdateTime(DateUtils.now());
                                kdlGM.setUpdateUser(ShiroUtils.getUserId());
                                kdlGM.setId(rgrList.get(0).getId());
                                kdlPODMapper.updateById(kdlGM);
                            }else {
                                kdlPODMapper.insert(kdlGM);
                            }
                        }
                        //return JsonResult.success(result);
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                }
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public String getRGRMaxSyncTime() {
        return kdlRGRMapper.GetMaxSyncTime();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public String getCHGMaxSyncTime() {
        return kdlRGRMapper.GetCHGMaxSyncTime();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncRGR(RGRQuery query) {
        StringBuilder sb = new StringBuilder();
        //String startTime = kdlRGRMapper.GetMaxSyncTime();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sb.append("<CAH3PL>");
        sb.append("<Head>");
        sb.append("<PrincipalID>" + CommonConfig.kdlCompanyId + "</PrincipalID>");
        sb.append("<DocType>RGR</DocType>");
        sb.append("<StartTime>" + query.getStarttime()+ "</StartTime>");
        sb.append("<EndTime>" + query.getEndtime() + "</EndTime>");
        sb.append("</Head>");
        sb.append("</CAH3PL>");
        NcServiceLog log = new NcServiceLog();
        String body = sb.toString();
        log.setRequestBody(body);
        log.setSubmitTime(DateUtils.now());
        log.setSubmitNo(query.getPrincipalid()+"_"+query.getDoctype());
        try {
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            StringBuilder sbResult = new StringBuilder();
            try {
                result = request.postData(CommonConfig.kdlSandbox? SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST:SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                //result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><CAH3PL><Head><FunCode>9000</FunCode><Remark>读取数据成功</Remark><PrincipalID>111385</PrincipalID></Head><Details><Detail><QFFNo>000200067786</QFFNo><Inspectiontype/><Plant>T150</Plant><CAHMaterialCode>000000000030518554</CAHMaterialCode><BATCH>0006403219</BATCH><ItemNo>0118030301</ItemNo><VendorBatch>230130</VendorBatch><ManufactureDate>2023-05-15</ManufactureDate><ExpiredDate>2025-05-14</ExpiredDate><Result>外观破损</Result><Qty>0.000</Qty><Location/><OrderNo>1528CD2401</OrderNo><ERDAT>2024-02-18</ERDAT><BoxFlag>ZX</BoxFlag><BoxNo/></Detail></Details></CAH3PL>";
                log.setResponseBody(result);
                log.setResponseCode("");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementGR, "Head");
                    Element detailResult = XmlUtil.getElement(elementGR, "Details");
                    String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                    String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存
                        KdlRGR kdlGM = new KdlRGR();
                        //遍历明细Details
                        Element detail = null;
                        String syncTime = DateUtil.now();
                        Map<String,Object> param = new HashMap<>();
                        List<KdlRGR> rgrList = null;
//                        kdlRGRMapper.delete(new QueryWrapper<KdlRGR>().eq("vendorpo",CommonUtils.XmlGetNodeContent(headResult, "VendorPO")));
                        for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            param.clear();
                            detail = (Element) detailResult.getChildNodes().item(i);
                            kdlGM.setPrincipalid(query.getPrincipalid());
                            kdlGM.setPrincipalname(CommonUtils.XmlGetNodeContent(headResult, "PrincipalName"));
                            kdlGM.setVendorpo(CommonUtils.XmlGetNodeContent(headResult, "VendorPO"));
                            kdlGM.setDoctype(CommonUtils.XmlGetNodeContent(headResult, "DocType"));
                            kdlGM.setRgrdate(CommonUtils.XmlGetNodeContent(headResult, "RGRDate"));
                            kdlGM.setSn(CommonUtils.XmlGetNodeContent(detail, "SN"));
                            kdlGM.setMaterialcode(CommonUtils.XmlGetNodeContent(detail, "MaterialCode"));
                            kdlGM.setVendorbatch(CommonUtils.XmlGetNodeContent(detail, "VendorBatch"));
                            kdlGM.setRgrquantity(new BigDecimal(CommonUtils.XmlGetNodeContent(detail, "RGRQuantity", 0)));
                            kdlGM.setVendoruom(CommonUtils.XmlGetNodeContent(detail, "VendorUOM"));
                            kdlGM.setRgrreason(CommonUtils.XmlGetNodeContent(detail, "RGRReason"));
                            kdlGM.setRgrnamr(CommonUtils.XmlGetNodeContent(detail, "RGRNamr"));
                            kdlGM.setCompanycode(CommonUtils.XmlGetNodeContent(detail, "CompanyCode"));
                            kdlGM.setPk(CommonUtils.XmlGetNodeContent(detail, "PK"));

                            kdlGM.setSyncTime(syncTime);
                            param.put("pk",kdlGM.getPk());
                            rgrList = kdlRGRMapper.selectByMap(param);
                            if(rgrList.size()>0){
                                kdlGM.setId(rgrList.get(0).getId());
                                kdlGM.setUpdateTime(DateUtils.now());
                                kdlGM.setUpdateUser(ShiroUtils.getUserId());
                                kdlRGRMapper.updateById(kdlGM);
                            }else {
                                kdlRGRMapper.insert(kdlGM);
                            }
                        }
                        //return JsonResult.success(result);
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                }
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(StringUtils.trim(ex.getMessage()));
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            log.setResponseBody(StringUtils.trim(ex.getMessage()));
            log.setResponseCode("500");
            log.setResponseResult("");
            ncServiceLogService.save(log);
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncCHG(RGRQuery query) {
        StringBuilder sb = new StringBuilder();
        //String startTime = kdlRGRMapper.GetMaxSyncTime();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sb.append("<CAH3PL>");
        sb.append("<Head>");
        sb.append("<PrincipalID>" + CommonConfig.kdlCompanyId + "</PrincipalID>");
        sb.append("<DocType>CHG</DocType>");
        sb.append("<StartTime>" + query.getStarttime()+ "</StartTime>");
        sb.append("<EndTime>" + query.getEndtime() + "</EndTime>");
        sb.append("</Head>");
        sb.append("</CAH3PL>");
        NcServiceLog log = new NcServiceLog();
        String body = sb.toString();
        log.setRequestBody(body);
        log.setSubmitTime(DateUtils.now());
        log.setSubmitNo(query.getPrincipalid()+"_"+query.getDoctype());
        try {
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            StringBuilder sbResult = new StringBuilder();
            try {
                result = request.postData(CommonConfig.kdlSandbox? SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST:SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                //result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><CAH3PL><Head><FunCode>9000</FunCode><Remark>读取数据成功</Remark><PrincipalID>111385</PrincipalID></Head><Details><Detail><QFFNo>000200067786</QFFNo><Inspectiontype/><Plant>T150</Plant><CAHMaterialCode>000000000030518554</CAHMaterialCode><BATCH>0006403219</BATCH><ItemNo>0118030301</ItemNo><VendorBatch>230130</VendorBatch><ManufactureDate>2023-05-15</ManufactureDate><ExpiredDate>2025-05-14</ExpiredDate><Result>外观破损</Result><Qty>0.000</Qty><Location/><OrderNo>1528CD2401</OrderNo><ERDAT>2024-02-18</ERDAT><BoxFlag>ZX</BoxFlag><BoxNo/></Detail></Details></CAH3PL>";
                log.setResponseBody(result);
                log.setResponseCode("");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementGR, "Head");
                    Element detailResult = XmlUtil.getElement(elementGR, "Details");
                    String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                    String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存

                        KdlHC kdlHC = new KdlHC();
                        //遍历明细Details
                        Element detail = null;
                        String syncTime = DateUtil.now();
                        Map<String,Object> param = new HashMap<>();
                        List<KdlHC> rgrList = null;
//                        kdlRGRMapper.delete(new QueryWrapper<KdlRGR>().eq("vendorpo",CommonUtils.XmlGetNodeContent(headResult, "VendorPO")));
                        for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            param.clear();
                            detail = (Element) detailResult.getChildNodes().item(i);
                            kdlHC.setPrincipalid(query.getPrincipalid());
                            kdlHC.setSapbatch(CommonUtils.XmlGetNodeContent(detail, "SAPbatch"));
                            kdlHC.setOldManufacturedate(CommonUtils.XmlGetNodeContent(detail, "OLD_Manufacturedate"));
                            kdlHC.setOldBatch(CommonUtils.XmlGetNodeContent(detail, "OLD_Batch"));
                            kdlHC.setNewBatch(CommonUtils.XmlGetNodeContent(detail, "NEW_Batch"));
                            kdlHC.setNewManufacturedate(CommonUtils.XmlGetNodeContent(detail, "NEW_Manufacturedate"));
                            kdlHC.setOldExpireddate(CommonUtils.XmlGetNodeContent(detail, "OLD_Expireddate"));
                            kdlHC.setNewExpireddate(CommonUtils.XmlGetNodeContent(detail, "NEW_Expireddate"));
                            kdlHC.setBoxflag(CommonUtils.XmlGetNodeContent(detail, "BoxFlag"));
                            kdlHC.setChanger(CommonUtils.XmlGetNodeContent(detail, "Changer"));
                            kdlHC.setChangeDate(CommonUtils.XmlGetNodeContent(detail, "Change_Date"));
                            kdlHC.setMaterialcode(CommonUtils.XmlGetNodeContent(detail, "MaterialCode"));
                            kdlHC.setPlant(CommonUtils.XmlGetNodeContent(detail, "Plant"));
                            kdlHC.setBoxno(CommonUtils.XmlGetNodeContent(detail, "BoxNo"));
                            kdlHC.setIdoc(CommonUtils.XmlGetNodeContent(detail, "Idoc"));
                            kdlHC.setSyncTime(CommonUtils.XmlGetNodeContent(detail, "Time"));


                            param.put("idoc",kdlHC.getIdoc() );
                            rgrList = kdlHCMapper.selectByMap(param);
                            if(!rgrList.isEmpty()){
                                kdlHC.setId(rgrList.get(0).getId());
                                kdlHC.setUpdateTime(DateUtils.now());
                                kdlHC.setUpdateUser(ShiroUtils.getUserId());
                                kdlHCMapper.updateById(kdlHC);
                            }else {
                                kdlHCMapper.insert(kdlHC);
                            }
                        }
                        //return JsonResult.success(result);
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                }
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(StringUtils.trim(ex.getMessage()));
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            log.setResponseBody(StringUtils.trim(ex.getMessage()));
            log.setResponseCode("500");
            log.setResponseResult("");
            ncServiceLogService.save(log);
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public String getZBFEMaxSyncTime() {
        return kdlZBFEMapper.GetMaxSyncTime();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult syncZBFE(RGRQuery query) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + query.getPrincipalid() + "</PrincipalID>");
            sb.append("<DocType>ZBFE</DocType>");
            sb.append("<StartTime>" + query.getStarttime() + "</StartTime>");
            sb.append("<EndTime>" + query.getEndtime() + "</EndTime>");
            sb.append("</Head>");
            sb.append("</CAH3PL>");
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            String body = sb.toString();
            log.setSubmitNo(query.getPrincipalid()+"_"+query.getDoctype());

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox? SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX_TEST:SHYPConstants.KDL_GETCONFIRMATION_URL_SUFFIX, "", null, body, config.getUseSandbox());
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                for (int j = 0; j < elementG.getChildNodes().getLength(); j++) {
                    Element elementGR = (Element) elementG.getChildNodes().item(j);
                    Element headResult = XmlUtil.getElement(elementGR, "Head");
                    Element detailResult = XmlUtil.getElement(elementGR, "Details");
                    String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                    String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                    log.setResponseBody(result);
                    log.setResponseCode(resCode);
                    log.setResponseResult(resRemark);
                    ncServiceLogService.save(log);
                    if ("9000".equals(resCode)) {
                        //解析返回的数据并保存
                        KdlZBFE purchasein = new KdlZBFE();
                        KdlZBFEB purchaseinB = new KdlZBFEB();
                        purchasein.setPrincipalid(CommonUtils.XmlGetNodeContent(headResult, "PrincipalID"));
                        purchasein.setPrincipalname(CommonUtils.XmlGetNodeContent(headResult, "PrincipalName"));
                        purchasein.setVendorso(CommonUtils.XmlGetNodeContent(headResult, "VendorSO"));
                        purchasein.setDoctype(CommonUtils.XmlGetNodeContent(headResult, "DocType"));
                        purchasein.setCustomername(CommonUtils.XmlGetNodeContent(headResult, "CustomerName"));
                        purchasein.setDeliveryaddress(CommonUtils.XmlGetNodeContent(headResult, "DeliveryAddress"));
                        purchasein.setPlantaddress(CommonUtils.XmlGetNodeContent(headResult, "PlantAddress"));
                        purchasein.setCompanycode(CommonUtils.XmlGetNodeContent(headResult, "CompanyCode"));


                        String pgidate = DateUtil.format(DateUtil.parse(CommonUtils.XmlGetNodeContent(headResult, "PGIDate"), DateUtils.YYYYMMDD), DateUtils.YYYY_MM_DD);
                        purchasein.setPgidate(pgidate);
                        purchasein.setPgiid(CommonUtils.XmlGetNodeContent(headResult, "PGIID"));
                        purchasein.setPgiidname(CommonUtils.XmlGetNodeContent(headResult, "PGIIDName"));
                        purchasein.setRemark(CommonUtils.XmlGetNodeContent(headResult, "Remark"));
                        List<KdlZBFE> list = kdlZBFEMapper.selectList(new QueryWrapper<KdlZBFE>().eq("vendorso", purchasein.getVendorso()));
                        if (list.size() == 0) {
                            kdlZBFEMapper.insert(purchasein);
                        } else {
                            purchasein.setUpdateTime(DateUtils.now());
                            purchasein.setId(list.get(0).getId());
                            kdlZBFEMapper.updateById(purchasein);
                        }
                        //遍历明细Details
                        Element detail = null;
                        for (int i = 0; i < detailResult.getChildNodes().getLength(); i++) {
                            detail = (Element) detailResult.getChildNodes().item(i);
                            purchaseinB.setPid(purchasein.getId());
                            purchaseinB.setVendorsolineno(CommonUtils.XmlGetNodeContent(detail, "VendorSOLineNo"));
                            purchaseinB.setCahdnno(CommonUtils.XmlGetNodeContent(detail, "CAHDNNO"));
                            purchaseinB.setMaterialcode(CommonUtils.XmlGetNodeContent(detail, "MaterialCode"));
                            purchaseinB.setCahmaterialcode(CommonUtils.XmlGetNodeContent(detail, "CAHMaterialCode"));
                            purchaseinB.setMaterialdes(CommonUtils.XmlGetNodeContent(detail, "MaterialDes"));
                            purchaseinB.setComdescription(CommonUtils.XmlGetNodeContent(detail, "ComDescription"));
                            purchaseinB.setMaterialspec(CommonUtils.XmlGetNodeContent(detail, "MaterialSpec"));
                            purchaseinB.setMaterialform(CommonUtils.XmlGetNodeContent(detail, "MaterialForm"));
                            purchaseinB.setRegistno(CommonUtils.XmlGetNodeContent(detail, "RegistNo"));
                            purchaseinB.setManufacturername(CommonUtils.XmlGetNodeContent(detail, "ManufacturerName"));
                            purchaseinB.setSubmaufacturername(CommonUtils.XmlGetNodeContent(detail, "SubMaufacturerName"));
                            purchaseinB.setVendorissueplant(CommonUtils.XmlGetNodeContent(detail, "VendorIssuePlant"));
                            purchaseinB.setCahissueplant(CommonUtils.XmlGetNodeContent(detail, "CAHIssuePlant"));
                            purchaseinB.setPgiquantity(CommonUtils.XmlGetNodeContent(detail, "PGIQuantity", 0));
                            purchaseinB.setPgiitemfinish(CommonUtils.XmlGetNodeContent(detail, "PGIItemFinish"));
                            purchaseinB.setCahuom(CommonUtils.XmlGetNodeContent(detail, "CAHUOM"));
                            purchaseinB.setVendoruom(CommonUtils.XmlGetNodeContent(detail, "VendorUOM"));
                            purchaseinB.setVendorbatch(CommonUtils.XmlGetNodeContent(detail, "VendorBatch"));
                            purchaseinB.setSerialno(CommonUtils.XmlGetNodeContent(detail, "SerialNo"));
                            purchaseinB.setExpireddate(CommonUtils.XmlGetNodeContent(detail, "ExpiredDate"));
                            purchaseinB.setManufacturedate(CommonUtils.XmlGetNodeContent(detail, "ManufactureDate"));
                            purchaseinB.setSterilizationbatch(CommonUtils.XmlGetNodeContent(detail, "SterilizationBatch"));
                            purchaseinB.setBoxno(CommonUtils.XmlGetNodeContent(detail, "BoxNo"));
                            purchaseinB.setBoxflag(CommonUtils.XmlGetNodeContent(detail, "BoxFlag"));
                            purchaseinB.setSyncTime(CommonUtils.XmlGetNodeContent(detail, "Time"));

                            List<KdlZBFEB> list1 = kdlZBFEBMapper.selectList(new QueryWrapper<KdlZBFEB>().eq("vendorsolineno", purchaseinB.getVendorsolineno()).eq("cahdnno",purchaseinB.getCahdnno()));
                            if (list1.size() == 0) {
                                kdlZBFEBMapper.insert(purchaseinB);
                            } else {
                                purchaseinB.setUpdateTime(DateUtils.now());
                                purchaseinB.setId(list1.get(0).getId());
                                kdlZBFEBMapper.updateById(purchaseinB);
                            }
                        }

                        //return JsonResult.success(result);
                    } else {
                        sbResult.append(resCode + ":" + resRemark);
                    }
                }
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }

    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getRejectDetail(String orderno) {
        return JsonResult.success(kdlRGRMapper.getRejectDetail(orderno));
    }


    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getZBFEDetail(Integer id) {
        return JsonResult.success(kdlZBFEMapper.getZBFEDetail(id));
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult GetConfirmation(String body) {
        return null;
    }

    /*
    获取NC采购订单列表
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getNCPOOrderList(BaseQuery query) {
        NCPOOrderQuery ncpoOrderQuery = (NCPOOrderQuery)query;
        IPage<NCPOOrder> page = new Page<>(ncpoOrderQuery.getPage(), ncpoOrderQuery.getLimit());
        IPage<NCPOOrder> pageData = ncpoOrderMapper.getNCPOOrderList(page, ncpoOrderQuery);
        return JsonResult.success(pageData);

    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getNCBilltypeList(String orgcode,String bill) {
        return JsonResult.success(ncpoOrderMapper.getBilltypeList(orgcode,bill));
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getNCPOOrderDetailList(String pkOrder) {
        List<NCPOOrderDetail> listData = ncpoOrderMapper.getNCPOOrderDetailList(pkOrder);
        return JsonResult.success(listData);

    }

    /*
    * 获取采购入库验收记录*/
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getPurchaseinInspectionDetail(String orderno) {
        List<PurchaseinInspectionResult> listData = kdlPurchaseinMapper.getPurchaseinInspectionDetail(orderno);
        return JsonResult.success(listData);

    }

    /*
    获取NC其他出库列表
    */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getNCGeneralOutList(BaseQuery query) {
        NCGeneralOutQuery ncpoOrderQuery = (NCGeneralOutQuery)query;
        IPage<NCGeneraloutH> page = new Page<>(ncpoOrderQuery.getPage(), ncpoOrderQuery.getLimit());
        IPage<NCGeneraloutH> pageData = ncGeneraloutHMapper.getNCGeneralOutList(page, ncpoOrderQuery);
        return JsonResult.success(pageData);

    }
    /*
    获取NC其他出库列表
    */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getNCGeneralOutDetailList(String cgeneralhid) {
        List<NCGeneraloutB> listData = ncGeneraloutHMapper.getNCGeneralOutDetail(cgeneralhid);
        return JsonResult.success(listData);

    }
    /*
    获取NC其他入库列表
    */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getNCGeneralInList(BaseQuery query) {
        NCGeneralOutQuery ncpoOrderQuery = (NCGeneralOutQuery)query;
        IPage<NCGeneralinH> page = new Page<>(ncpoOrderQuery.getPage(), ncpoOrderQuery.getLimit());
        IPage<NCGeneralinH> pageData = ncGeneralinHMapper.getNCGeneralInList(page, ncpoOrderQuery);
        return JsonResult.success(pageData);

    }
    /*
    获取NC其他出库列表
    */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getNCGeneralInDetailList(String cgeneralhid) {
        List<NCGeneralinB> listData = ncGeneralinHMapper.getNCGeneralinDetail(cgeneralhid);
        return JsonResult.success(listData);

    }

    /*
    获取NC采购订单列表
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getNCSOOrderList(BaseQuery query) {
        NCSOOrderQuery ncpoOrderQuery = (NCSOOrderQuery)query;
        IPage<NCSOOrder> page = new Page<>(ncpoOrderQuery.getPage(), ncpoOrderQuery.getLimit());
        IPage<NCSOOrder> pageData = ncsoOrderMapper.getNCSOOrderList(page, ncpoOrderQuery);
        return JsonResult.success(pageData);

    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getNCSOOrderDetailList(String pkOrder) {
        List<NCSOOrderDetail> listData = ncsoOrderMapper.getNCSOOrderDetailList(pkOrder);
        return JsonResult.success(listData);

    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getNCOnHandList(BaseQuery query) {
        KdlNcOnhandQuery ncQuery = (KdlNcOnhandQuery)query;
        IPage<KdlNcOnhand> page = new Page<>(ncQuery.getPage(), ncQuery.getLimit());
        IPage<KdlNcOnhand> pageData = kdlNcOnhandMapper.getNCOnHandList(page, ncQuery);
        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getKdlInventory(BaseQuery query) {
        KdlInventoryQuery ncQuery = (KdlInventoryQuery)query;
        IPage<KdlInventoryVo> page = new Page<>(ncQuery.getPage(), ncQuery.getLimit());
        QueryWrapper<KdlInventory> queryWrapper = new QueryWrapper<>();
        IPage<KdlInventoryVo> pageData = kdlInventoryMapper.getKdlInventory(page, ncQuery);
        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getKdlQffFeedback(BaseQuery query) {
        KdlQffFeedbackQuery ncQuery = (KdlQffFeedbackQuery)query;
        IPage<KdlQffFeedbackVo> page = new Page<>(ncQuery.getPage(), ncQuery.getLimit());
        IPage<KdlQffFeedbackVo> pageData = kdlQffFeedbackMapper.getQffFeedbackList(page, ncQuery);
        return JsonResult.success(pageData);
    }


    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getKdlTransReport(BaseQuery query) {
        KdlTransReportQuery ncQuery = (KdlTransReportQuery)query;
        IPage<KdlTransReportVo> page = new Page<>(ncQuery.getPage(), ncQuery.getLimit());
        QueryWrapper<KdlTransReportVo> queryWrapper = new QueryWrapper<>();
        IPage<KdlTransReportVo> pageData = kdlTransReportMapper.getTransReportList(page, ncQuery);

        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getKdlMaintainReport(BaseQuery query) {
        KdlMaintainReportQuery ncQuery = (KdlMaintainReportQuery)query;
        IPage<KdlMaintainReportVo> page = new Page<>(ncQuery.getPage(), ncQuery.getLimit());
        QueryWrapper<KdlMaintainReportVo> queryWrapper = new QueryWrapper<>();
        IPage<KdlMaintainReportVo> pageData = kdlMaintainReportMapper.getMaintainReportList(page, ncQuery);

        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getKdlRGR(BaseQuery query) {
        KdlRGRQuery ncQuery = (KdlRGRQuery)query;
        IPage<KdlRGRVo> page = new Page<>(ncQuery.getPage(), ncQuery.getLimit());
        IPage<KdlRGRVo> pageData = kdlRGRMapper.getRGRList(page, ncQuery);
        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getKdlZBFE(BaseQuery query) {
        KdlRGRQuery ncQuery = (KdlRGRQuery)query;
        IPage<KdlZBFE> page = new Page<>(ncQuery.getPage(), ncQuery.getLimit());
        QueryWrapper<KdlZBFE> queryWrapper = new QueryWrapper<>();
        IPage<KdlZBFE> pageData = kdlZBFEMapper.selectPage(page, queryWrapper);
        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getKdlPOD(BaseQuery query) {
        KdlPODQuery ncQuery = (KdlPODQuery)query;
        IPage<KdlPODVo> page = new Page<>(ncQuery.getPage(), ncQuery.getLimit());
        IPage<KdlPODVo> pageData = kdlPODMapper.getPODList(page, ncQuery);
        return JsonResult.success(pageData);
    }

    /*
    * 康德乐采购质检回传记录回写NC
    * */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitInspectToNC(Integer id,boolean sendAll) {
        String body = "";
        StringBuilder sb = new StringBuilder();
        StringBuilder sbCheck = new StringBuilder();
        KdlPurchaseinQuery kdlPurchaseinQuery = new KdlPurchaseinQuery();
        kdlPurchaseinQuery.setId(id);
        kdlPurchaseinQuery.setPage(1);
        kdlPurchaseinQuery.setLimit(1);
        // 获取数据列表
//        IPage<KdlPurchasein> page = new Page<>(kdlPurchaseinQuery.getPage(), kdlPurchaseinQuery.getLimit());
//        IPage<KdlPurchasein> pageData = kdlPurchaseinMapper.getPurchaseinList(page, kdlPurchaseinQuery);
        KdlPurchasein entity = kdlPurchaseinMapper.selectById(id);
        if(StringUtils.isNull(entity))
        {
            return JsonResult.error("无效的id:"+id.toString());
        }
        //检查制单人、审批人是否配置
        String billMaker = getNCUserId("Z01",DataSourceType.SINESYS);
        if(StringUtils.isEmpty(billMaker)){
            return JsonResult.error("采购入库质检回传Z01对应的制单人未配置");
        }
        //KdlPurchasein entity = pageData.getRecords().get(0);
        //检查组织代码
        if(StringUtils.isEmpty(entity.getCompanycode())){
            return JsonResult.error("采购入库质检回传对应的组织代码为空");
        }
        List<PurchaseinInspectionResult> checkList =sendAll?kdlPurchaseinMapper.getPurchaseinInspectionSendResultAll(entity.getId()): kdlPurchaseinMapper.getPurchaseinInspectionSendResult(entity.getId());
        //箱型、箱号校验通过的采购入库质检结果
        List<PurchaseinInspectionResult> list = new ArrayList<>();

        NCPurchaseIn ncPurchaseIn = null;
        PurchaseInBodys bodys = new PurchaseInBodys();
        String batchcode="";
        String cwarehouseid = "";
        List<PurchaseInBodys> bodysList = new ArrayList<>();
        //遍历采购入库质检，校验箱型、箱号
        //boxflag:LX、PX还需要校验箱号
        for (int i = 0; i < checkList.size(); i++) {
            if(StringUtils.isEmpty(checkList.get(i).getBoxflag())){
                //避免质检记录太多，导致前端消息窗口显示不下，每两行错误信息合并一行显示
                if(i>0 && (i+1)%2==0){
                    sbCheck.append("采购质检入库的检验批号："+checkList.get(i).getInspectionlot()+"的箱型为空<br/>");
                }else{
                    sbCheck.append("采购质检入库的检验批号："+checkList.get(i).getInspectionlot()+"的箱型为空  ");
                }
                continue;
            }else{
                if(StringUtils.trim(checkList.get(i).getBoxflag()).equals("PX") && StringUtils.isEmpty(checkList.get(i).getBoxno())){
                    if(i>0 && (i+1)%2==0){
                        sbCheck.append("采购质检入库的检验批号：" + checkList.get(i).getInspectionlot() + "的箱型为" + checkList.get(i).getBoxflag() + ",箱号不能为空<br/>");
                    }else{
                        sbCheck.append("采购质检入库的检验批号：" + checkList.get(i).getInspectionlot() + "的箱型为" + checkList.get(i).getBoxflag() + ",箱号不能为空  ");
                    }
                    continue;
                }
            }
            list.add(checkList.get(i));
        }
        if(!StringUtils.isEmpty(sbCheck.toString())){
            NcServiceLog ncServiceLog = new NcServiceLog();
            ncServiceLog.setSubmitNo(entity.getVendorpo()+"_PurchaseIn");
            ncServiceLog.setRequestBody("");
            ncServiceLog.setSubmitTime(DateUtils.now());
            ncServiceLog.setResponseBody(sbCheck.toString());
            ncServiceLog.setResponseCode("500");
            ncServiceLog.setResponseResult("");
            String dataSource = DynamicDataSource.getDataSource();
            DynamicDataSource.setDataSource(DataSourceType.MASTER.getName());
            ncServiceLogService.save(ncServiceLog);
            DynamicDataSource.setDataSource(dataSource);
        }


        for (int i = 0; i < list.size(); i++) {
            bodysList.clear();
            ncPurchaseIn = new NCPurchaseIn();
            ncPurchaseIn.setInitid("PurchaseIn");
//            ncPurchaseIn.setDbilldate(entity.getGrdate());
            //单据日期取质检日期 2024-06-17
            ncPurchaseIn.setDbilldate(list.get(i).getInspectiondate1());
            ncPurchaseIn.setVbillcode(list.get(i).getCwarehouseid()+list.get(i).getInspectionlot());
            ncPurchaseIn.setCvendorid(entity.getVendorcode());
            ncPurchaseIn.setApprover(billMaker);
            ncPurchaseIn.setBillmaker(billMaker);
            ncPurchaseIn.setPk_org(entity.getCompanycode());
            //工厂代码+库位号
            cwarehouseid = list.get(i).getGrplant()+list.get(i).getCwarehouseid();
            ncPurchaseIn.setCwarehouseid(cwarehouseid);
            bodys.setCfirstbillbid(list.get(i).getCfirstbillbid());
            bodys.setCmaterialvid(list.get(i).getCmaterialvid());
            bodys.setNnum(list.get(i).getNnum());
            bodys.setCstateid(list.get(i).getCstateid());
            bodys.setVlotno(list.get(i).getVlotno());
            bodys.setVlotno_dprodate(list.get(i).getVlotnoDprodate());
            bodys.setVlotno_vinvaliddate(list.get(i).getVlotnoVinvaliddate());

            batchcode = CommonUtils.getBatchCode(entity.getCompanycode(),list.get(i).getVlotno(),list.get(i).getBoxflag(),list.get(i).getSapbatch());
            bodys.setVbatchcode(batchcode);
            bodys.setVbatchcode_vdef3("");
            bodys.setVbatchcode_vdef15("");
            bodys.setVbatchcode_vdef11(list.get(i).getSapbatch());
            bodys.setVbatchcode_vdef12(list.get(i).getBoxflag());
            bodys.setVbatchcode_vdef16(list.get(i).getBoxno());
            bodysList.add(bodys);
            ncPurchaseIn.setBodys(bodysList);
            body = JSON.toJSONString(ncPurchaseIn);
            JsonResult result = sendToReviewLog.callEsbKdl("PurchaseIn",entity.getVendorpo()+"_"+list.get(i).getCwarehouseid()+"_"+list.get(i).getInspectionlot(),body);
            if(result.getCode()>0){
                sb.append(result.getMsg());
                if(result.getMsg().contains("重复")){
                    //更新回写状态
                    DynamicDataSource.setDataSource("sinesys");
                    KdlInspectionresultStatus inspectionresultStatus = new KdlInspectionresultStatus();
                    inspectionresultStatus.setCwarehouseid(list.get(i).getCwarehouseid());
                    inspectionresultStatus.setInspectionlot(list.get(i).getInspectionlot());
                    Map<String,Object> param = new HashMap<>();
                    param.put("cwarehouseid",list.get(i).getCwarehouseid());
                    param.put("inspectionlot",list.get(i).getInspectionlot());
                    if(kdlInspectionresultStatusMapper.selectByMap(param).size()==0) {
                        inspectionresultStatus.setStatus(Constants.NC_SUBMIT_STATUS);
                        kdlInspectionresultStatusMapper.insert(inspectionresultStatus);
                    }else{
                        UpdateWrapper<KdlInspectionresultStatus> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.set("status",Constants.NC_SUBMIT_STATUS).eq("cwarehouseid",list.get(i).getCwarehouseid()).eq("inspectionlot",list.get(i).getInspectionlot());
                        kdlInspectionresultStatusMapper.update(new KdlInspectionresultStatus(),updateWrapper);
                    }
                }
            }else {
                //更新回写状态
                DynamicDataSource.setDataSource("sinesys");
                KdlInspectionresultStatus inspectionresultStatus = new KdlInspectionresultStatus();
                inspectionresultStatus.setCwarehouseid(list.get(i).getCwarehouseid());
                inspectionresultStatus.setInspectionlot(list.get(i).getInspectionlot());
                inspectionresultStatus.setStatus(Constants.NC_SUBMIT_STATUS);
                Map<String,Object> param = new HashMap<>();
                param.put("cwarehouseid",list.get(i).getCwarehouseid());
                param.put("inspectionlot",list.get(i).getInspectionlot());
                if(kdlInspectionresultStatusMapper.selectByMap(param).size()==0) {
                    inspectionresultStatus.setStatus(Constants.NC_SUBMIT_STATUS);
                    kdlInspectionresultStatusMapper.insert(inspectionresultStatus);
                }else{
                    UpdateWrapper<KdlInspectionresultStatus> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("status",Constants.NC_SUBMIT_STATUS).eq("cwarehouseid",list.get(i).getCwarehouseid()).eq("inspectionlot",list.get(i).getInspectionlot());
                    kdlInspectionresultStatusMapper.update(new KdlInspectionresultStatus(),updateWrapper);
                }
                //UpdateWrapper<KdlPurchaseinB> updateWrapper = new UpdateWrapper<>();
                //updateWrapper.set("status", Constants.NC_SUBMIT_STATUS).eq("pid", entity.getId()).eq("inspectionlot", entity.getInspectionlot());
                //kdlPurchaseinBMapper.update(new KdlPurchaseinB(), updateWrapper);
            }
        }
        if(list.size()>0) {
            return StringUtils.isEmpty(sb.toString()) ? JsonResult.success() : JsonResult.error(sb.toString());
        }else
        {
            return StringUtils.isEmpty(sbCheck.toString()) ? JsonResult.success() : JsonResult.error(sbCheck.toString());
        }
    }

    /*
     * 康德乐采购异常反馈的移库结果，回写NC采购入库
     * @param id 移库结果记录id
     * */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitFeedbackInspectToNC(String orderno) {
        String body = "";
        StringBuilder sb = new StringBuilder();
        Map<String,Object> paramOrder = new HashMap<>();
        paramOrder.put("orderno",orderno);
        List<KdlGM> entityList = kdlGMMapper.selectByMap(paramOrder);
        if(entityList.size()==0)
        {
            return JsonResult.error("无效的物料凭证号:"+orderno);
        }
        KdlGM entity = entityList.get(0);
        KdlPurchaseinB purchaseinB = kdlPurchaseinBMapper.getPBByMaterialbatch(entity.getItemno(),entity.getVendorbatch(),entity.getBoxflag());
        if(StringUtils.isNull(purchaseinB))
        {
            log.info("采购异常反馈的移库结果批号:"+entity.getVendorbatch()+"，在采购入库质检回传结果中不存在");
            return JsonResult.error("采购异常反馈的移库结果批号:"+entity.getVendorbatch()+"，在采购入库质检回传结果中不存在");
        }
        KdlPurchasein purchasein = kdlPurchaseinMapper.selectById(purchaseinB.getPid());
        if(StringUtils.isNull(purchasein))
        {
            log.info("采购异常反馈的移库结果批号:"+entity.getVendorbatch()+"，对应的采购入库质检回传结果不存在");
            return JsonResult.error("采购异常反馈的移库结果批号:"+entity.getVendorbatch()+"，对应的采购入库质检回传结果不存在");
        }
        //检查制单人、审批人是否配置
        String billMaker = getNCUserId("Z01",DataSourceType.SINESYS);
        if(StringUtils.isEmpty(billMaker)){
            log.info("采购入库质检回传Z01对应的制单人未配置");
            return JsonResult.error("采购入库质检回传Z01对应的制单人未配置");
        }
        //KdlPurchasein entity = pageData.getRecords().get(0);
        //检查组织代码
        if(StringUtils.isEmpty(entity.getCompanycode())){
            log.info("采购异常反馈移库结果对应的组织代码为空");
            return JsonResult.error("采购异常反馈移库结果对应的组织代码为空");
        }
        String batchcode="";
        String cwarehouseid = "";
        String vendorid=purchasein.getVendorcode();
        String cfirstbillbid = purchaseinB.getSn();
        List<PurchaseInBodys> bodysList = new ArrayList<>();
        List<KdlGMVo> companyList = kdlGMMapper.getOtherInCompanyList(orderno);
        for (KdlGMVo gmVo:companyList) {
            bodysList.clear();
            NCPurchaseIn ncPurchaseIn = new NCPurchaseIn();
            ncPurchaseIn.setInitid("PurchaseIn");
            ncPurchaseIn.setDbilldate(entity.getOrderdate());
            ncPurchaseIn.setVbillcode(gmVo.getCompanycode()+gmVo.getTolocation()+gmVo.getOrderno());
            //获取采购订单对应的供应商代码
            ncPurchaseIn.setCvendorid(vendorid);
            ncPurchaseIn.setApprover(billMaker);
            ncPurchaseIn.setBillmaker(billMaker);
            ncPurchaseIn.setPk_org(gmVo.getCompanycode());
            //工厂代码+库位号
            cwarehouseid = gmVo.getPlant() + gmVo.getTolocation();
            ncPurchaseIn.setCwarehouseid(cwarehouseid);
            //获取采购订单明细主键
            List<KdlGMVo> detailList = kdlGMMapper.getCompanyGMOtherInDetailList(gmVo.getOrderno(),gmVo.getCompanycode(),gmVo.getTolocation());
            for (KdlGMVo item : detailList) {
                PurchaseInBodys bodys = new PurchaseInBodys();
                bodys.setCfirstbillbid(cfirstbillbid);
                bodys.setCmaterialvid(item.getItemno());
                bodys.setNnum(item.getQty());
                bodys.setCstateid(this.getStockStatus(item.getPlant(), item.getTolocation()));
                bodys.setVlotno(item.getVendorbatch());
                bodys.setVlotno_dprodate(purchaseinB.getManufacturedate());
                bodys.setVlotno_vinvaliddate(purchaseinB.getExpireddate());

                batchcode = CommonUtils.getBatchCode(item.getCompanycode(), item.getVendorbatch(), item.getBoxflag(), item.getBatchno());
                bodys.setVbatchcode(batchcode);
                bodys.setVbatchcode_vdef3("");
                bodys.setVbatchcode_vdef15("");
                bodys.setVbatchcode_vdef12(item.getBoxflag());
                bodys.setVbatchcode_vdef16(item.getBoxno());
                bodysList.add(bodys);
            }
            ncPurchaseIn.setBodys(bodysList);
            body = JSON.toJSONString(ncPurchaseIn);
            JsonResult result = sendToReviewLog.callEsbKdl("PurchaseIn", gmVo.getCompanycode()+gmVo.getTolocation()+gmVo.getOrderno(), body);
            if (result.getCode() > 0) {
                sb.append(result.getMsg());
                if (result.getMsg().contains("重复")) {
                    //更新回写状态
                    DynamicDataSource.setDataSource("sinesys");
                    UpdateWrapper<KdlGM> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("status", Constants.NC_SUBMIT_STATUS).eq("orderno", gmVo.getOrderno()).eq("companycode", gmVo.getCompanycode()).eq("tolocation", gmVo.getTolocation());
                    kdlGMMapper.update(new KdlGM(), updateWrapper);
                }
            } else {
                //更新回写状态
                DynamicDataSource.setDataSource("sinesys");
                UpdateWrapper<KdlGM> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("status", Constants.NC_SUBMIT_STATUS).eq("orderno", gmVo.getOrderno()).eq("companycode", gmVo.getCompanycode()).eq("tolocation", gmVo.getTolocation());
                kdlGMMapper.update(new KdlGM(), updateWrapper);
            }
        }
        return StringUtils.isEmpty(sb.toString())?JsonResult.success():JsonResult.error(sb.toString());
    }

    /**
     * 康德乐销售退货回传记录回写NC
     * @param id
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitSaleReturnToNC(Integer id) {
        String body = "";
        StringBuilder sb = new StringBuilder();
        KdlZ05kdl entity = kdlZ05kdlMapper.selectById(id);
        if(StringUtils.isNull(entity))
        {
            return JsonResult.error("无效的id:"+id.toString());
        }
        //检查制单人、审批人是否配置
        String billMaker = getNCUserId("Z05",DataSourceType.SINESYS);
        if(StringUtils.isEmpty(billMaker)){
            return JsonResult.error("销售退货入库质检回传Z05对应的制单人未配置");
        }
        List<SaleReturnInspectionResult> list = kdlZ05kdlMapper.getSaleReturnInspectionSendResult(entity.getId());

        SaleOut2NC ncSaleOut = null;
        SaleOut2NC.Sale2NCDetail bodys = null;
        String batchcode="";
        String pk_order_b="";
        String vlotno = "";
        NcServiceLog ncServiceLog = new NcServiceLog();
        List<SaleOut2NC.Sale2NCDetail> bodysList = new ArrayList<>();
        for (int j = 0; j < list.size(); j++) {
            ncSaleOut = new SaleOut2NC();
            bodysList.clear();
            pk_order_b = list.get(j).getCfirstbillbid();
            vlotno = kdlSaleOutQcMapper.getNCVlotno(pk_order_b);
            //若批号不一致，记录日志并跳过回写NC
            if(!list.get(j).getVlotno().equals(vlotno)){
                ncServiceLog.setSubmitNo(list.get(j).getVendorso()+"_SaleOut");
                ncServiceLog.setRequestBody("");
                ncServiceLog.setSubmitTime(DateUtils.now());
                String msg = "销退批号信息校验异常：实物【" + list.get(j).getComdescription() + "】的批号【" + list.get(j).getVlotno() + "】批号相关信息同订单指令【" + vlotno + "】不一致";
                log.info(msg);
                sb.append(msg);
                ncServiceLog.setResponseBody(msg);
                ncServiceLog.setResponseCode("500");
                ncServiceLog.setResponseResult("");
                String dataSource = DynamicDataSource.getDataSource();
                DynamicDataSource.setDataSource(DataSourceType.MASTER.getName());
                ncServiceLogService.save(ncServiceLog);
                DynamicDataSource.setDataSource(dataSource);

                continue;
            }
            //若箱型为空，记录日志并跳过回写NC
            if(StringUtils.trim(list.get(j).getBoxflag()).equals("")){
                ncServiceLog.setSubmitNo(list.get(j).getVendorso()+"_SaleOut");
                ncServiceLog.setRequestBody("");
                ncServiceLog.setSubmitTime(DateUtils.now());
                String msg = "销退箱型信息校验异常：实物【" + list.get(j).getComdescription() + "】的箱型为空，无法回写NC";
                log.info(msg);
                sb.append(msg);
                ncServiceLog.setResponseBody(msg);
                ncServiceLog.setResponseCode("500");
                ncServiceLog.setResponseResult("");
                String dataSource = DynamicDataSource.getDataSource();
                DynamicDataSource.setDataSource(DataSourceType.MASTER.getName());
                ncServiceLogService.save(ncServiceLog);
                DynamicDataSource.setDataSource(dataSource);

                continue;
            }
            bodys = ncSaleOut.detailIns();
            ncSaleOut.setInitid("SaleOut");
            ncSaleOut.setPk_org(entity.getCompanycode());
            ncSaleOut.setVbillcode(list.get(j).getCwarehouseid()+list.get(j).getInspectionlot());
            ncSaleOut.setCcustomerid(entity.getCustomercode());
//            ncSaleOut.setDbilldate(entity.getGrdate());
            //单据日期取质检日期 2024-06-17
            ncSaleOut.setDbilldate(list.get(j).getInspectiondate1());
            ncSaleOut.setCwarehouseid(list.get(j).getGrplant()+list.get(j).getCwarehouseid());
            //ncSaleOut.setPk_org(CommonConfig.kdlOrgCode);
            ncSaleOut.setBillmaker(billMaker);
            ncSaleOut.setApprover(billMaker);
            bodys.setCsourcebillbid(list.get(j).getCfirstbillbid());
            bodys.setCmaterialvid(list.get(j).getCmaterialvid());
            bodys.setNnum(list.get(j).getNnum().negate().toString());
            //bodys.setVbatchcode(CommonUtils.getBatchCode(entity.getCompanycode(),list.get(j).getVlotno(), list.get(j).getBoxflag()));
            bodys.setVlotno(list.get(j).getVlotno());
            bodys.setVlotno_dprodate(list.get(j).getVlotnoDprodate());
            bodys.setVlotno_vinvaliddate(list.get(j).getVlotnoVinvaliddate());
            bodys.setVbatchcode_vdef12(list.get(j).getBoxflag());
            bodys.setVbatchcode_vdef16(list.get(j).getBoxno());
            String cstateid = getStockStatus(list.get(j).getGrplant(),list.get(j).getCwarehouseid());
            bodys.setCstateid(cstateid);
            batchcode = CommonUtils.getBatchCode(entity.getCompanycode(),list.get(j).getVlotno(),list.get(j).getBoxflag(),list.get(j).getSapbatch());
            //销退入库，批次号前加T，用来标记退货库存
            bodys.setVbatchcode("T"+batchcode);
            //bodys.setVbatchcode_vdef3("");
            //bodys.setVbatchcode_vdef15("");
            bodys.setVbatchcode_vdef12(list.get(j).getBoxflag());
            bodys.setVbatchcode_vdef16(list.get(j).getBoxno());
            bodysList.add(bodys);
            ncSaleOut.setDetailList(bodysList);
            body = JSON.toJSONString(ncSaleOut);
            JsonResult result = sendToReviewLog.callEsbKdl(ncSaleOut.getInitid(), entity.getVendorso(), body);
            if (result.getCode() > 0) {
                sb.append(result.getMsg());
            }
            else{
                //更新回写状态
                DynamicDataSource.setDataSource("sinesys");
                KdlInspectionresultStatus inspectionresultStatus = new KdlInspectionresultStatus();
                inspectionresultStatus.setCwarehouseid(list.get(j).getCwarehouseid());
                inspectionresultStatus.setInspectionlot(list.get(j).getInspectionlot());
                inspectionresultStatus.setStatus(Constants.NC_SUBMIT_STATUS);
                kdlInspectionresultStatusMapper.insert(inspectionresultStatus);
            }
        }
        return StringUtils.isEmpty(sb.toString())?JsonResult.success():JsonResult.error(sb.toString());
    }

    /**
     * 康德乐销售异常反馈的移库结果，回写NC销售出库
     * @param orderno 移库结果记录物料凭证号
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitFeedbackSaleReturnToNC(String orderno) {
        String body = "";
        StringBuilder sb = new StringBuilder();
        Map<String,Object> paramOrder = new HashMap<>();
        paramOrder.put("orderno",orderno);
        List<KdlGM> entityList = kdlGMMapper.selectByMap(paramOrder);
        if(entityList.size()==0)
        {
            return JsonResult.error("无效的物料凭证号:"+orderno);
        }
        KdlGM entity = entityList.get(0);
//        KdlZ05kdlB kdlZ05kdlB = kdlZ05kdlMapper.getZ05ByMaterialbatch(orderno);
//        if(StringUtils.isNull(kdlZ05kdlB))
//        {
//            log.info("销退异常反馈的移库结果批号:"+entity.getVendorbatch()+"，在销退回传结果中不存在");
//            return JsonResult.error("销退异常反馈的移库结果批号:"+entity.getVendorbatch()+"，在销退回传结果中不存在");
//        }
//        KdlZ05kdl kdlZ05kdl = kdlZ05kdlMapper.selectById(kdlZ05kdlB.getPid());
//        if(StringUtils.isNull(kdlZ05kdl))
//        {
//            log.info("销退异常反馈的移库结果批号:"+entity.getVendorbatch()+"，对应的销退回传结果不存在");
//            return JsonResult.error("销退异常反馈的移库结果批号:"+entity.getVendorbatch()+"，对应的销退回传结果不存在");
//        }

        //检查制单人、审批人是否配置
        String billMaker = getNCUserId("Z05",DataSourceType.SINESYS);
        if(StringUtils.isEmpty(billMaker)){
            log.info("销售退货入库质检回传Z05对应的制单人未配置");
            return JsonResult.error("销售退货入库质检回传Z05对应的制单人未配置");
        }
        //List<SaleReturnInspectionResult> list = kdlZ05kdlMapper.getSaleReturnInspectionSendResult(entity.getId());

        SaleOut2NC.Sale2NCDetail bodys = null;
        String batchcode="";
        String pk_order_b="";
        String vlotno = "";
        String msg = "";
        NcServiceLog log = new NcServiceLog();
        List<SaleOut2NC.Sale2NCDetail> bodysList = new ArrayList<>();
        List<KdlGMVo> companyList = kdlGMMapper.getOtherInCompanyList(orderno);
        for (KdlGMVo gmVo:companyList) {
            bodysList.clear();
            SaleOut2NC ncSaleOut = new SaleOut2NC();
            //vlotno = kdlSaleOutQcMapper.getNCVlotno(pk_order_b);
            //若批号不一致，记录日志并跳过回写NC
//            if (!entity.getVendorbatch().equals(vlotno)) {
//                log.setSubmitNo(gmVo.getCompanycode()+gmVo.getTolocation()+gmVo.getOrderno() + "_SaleOut");
//                log.setRequestBody("");
//                log.setSubmitTime(DateUtils.now());
//                msg = "销退批号信息校验异常：实物【" + kdlZ05kdlB.getComdescription() + "】的批号【" + entity.getVendorbatch() + "】批号相关信息同订单指令【" + vlotno + "】不一致";
//                sb.append(msg);
//                log.setResponseBody(msg);
//                log.setResponseCode("500");
//                log.setResponseResult("");
//                String dataSource = DynamicDataSource.getDataSource();
//                DynamicDataSource.setDataSource(DataSourceType.MASTER.getName());
//                ncServiceLogService.save(log);
//                DynamicDataSource.setDataSource(dataSource);
//                return JsonResult.error(msg);
//            }
            ncSaleOut.setInitid("SaleOut");
            ncSaleOut.setPk_org(gmVo.getCompanycode());
            ncSaleOut.setVbillcode(gmVo.getCompanycode()+gmVo.getTolocation()+gmVo.getOrderno());
            ncSaleOut.setDbilldate(entity.getOrderdate());
            ncSaleOut.setCwarehouseid(gmVo.getPlant() + gmVo.getTolocation());
            //ncSaleOut.setPk_org(CommonConfig.kdlOrgCode);
            ncSaleOut.setBillmaker(billMaker);
            ncSaleOut.setApprover(billMaker);
            List<KdlGMVo> detailList = kdlGMMapper.getCompanyGMOtherInDetailList(gmVo.getOrderno(), gmVo.getCompanycode(),gmVo.getTolocation());
            for (KdlGMVo item : detailList) {
                bodys = ncSaleOut.detailIns();
                KdlZ05kdlB kdlZ05kdlB = kdlZ05kdlMapper.getZ05ByMaterialbatch(orderno,item.getVendorbatch());
                if (kdlZ05kdlB == null) {
                    return JsonResult.error("查询结果为空，kdl传过来的sapbatch有问题" +
                            "select top 1 z05b.* from kdl_gm gm left join kdl_qff_feedback feedback on gm.principalorderno=feedback.principalorderno  inner join kdl_z05kdl so on feedback.orderno = so.vendorso inner join kdl_z05kdl_b z05b on z05b.pid = so.id and gm.batchno=z05b.sapbatch   where gm.orderno = '"+orderno+"' and z05b.vendorbatch='"+ item.getVendorbatch()+"'");
                }
                KdlZ05kdl kdlZ05kdl = kdlZ05kdlMapper.selectById(kdlZ05kdlB.getPid());
                ncSaleOut.setCcustomerid(kdlZ05kdl.getCustomercode());
                pk_order_b = kdlZ05kdlB.getVendorsolineno();

                bodys.setCsourcebillbid(pk_order_b);
                bodys.setCmaterialvid(item.getItemno());
                bodys.setNnum(item.getQty().negate().toString());
                //bodys.setVbatchcode(CommonUtils.getBatchCode(entity.getCompanycode(),list.get(j).getVlotno(), list.get(j).getBoxflag()));
                bodys.setVlotno(item.getVendorbatch());
                bodys.setVlotno_dprodate(kdlZ05kdlB.getManufacturedate());
                bodys.setVlotno_vinvaliddate(kdlZ05kdlB.getExpireddate());
                bodys.setVbatchcode_vdef11(item.getBatchno());
                bodys.setVbatchcode_vdef12(item.getBoxflag());
                bodys.setVbatchcode_vdef16(item.getBoxno());
                String cstateid = getStockStatus(item.getPlant(), item.getTolocation());
                bodys.setCstateid(cstateid);
                batchcode = CommonUtils.getBatchCode(item.getCompanycode(), item.getVendorbatch(), item.getBoxflag(), item.getBatchno());
                //销退入库，批次号前加T，用来标记退货库存
                bodys.setVbatchcode("T" + batchcode);
                //bodys.setVbatchcode_vdef3("");
                //bodys.setVbatchcode_vdef15("");
                bodysList.add(bodys);
            }
            ncSaleOut.setDetailList(bodysList);
            body = JSON.toJSONString(ncSaleOut);
            JsonResult result = sendToReviewLog.callEsbKdl(ncSaleOut.getInitid(), gmVo.getCompanycode()+gmVo.getTolocation()+gmVo.getOrderno(), body);
            if (result.getCode() > 0) {
                sb.append(result.getMsg());
            } else {
                //更新回写状态
                DynamicDataSource.setDataSource("sinesys");
                UpdateWrapper<KdlGM> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("status", Constants.NC_SUBMIT_STATUS).eq("orderno", gmVo.getOrderno()).eq("companycode", gmVo.getCompanycode()).eq("tolocation", gmVo.getTolocation());
                kdlGMMapper.update(new KdlGM(), updateWrapper);
            }
        }
        return StringUtils.isEmpty(sb.toString())?JsonResult.success():JsonResult.error(sb.toString());
    }
    /*
     * 康德乐销售出库回传记录回写NC
     * */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitSaleOutToNC(Integer id) {
        KdlSaleOut saleOut = kdlSaleOutMapper.selectById(id);
        List<KdlSaleOutB> saleOutBs = kdlSaleOutBMapper.getDetailsByVendorso(saleOut.getVendorso());
        Set<String> chlocationSet = saleOutBs.stream().map(KdlSaleOutB::getCahlocation).collect(Collectors.toSet());
        String msg = "";
        //分库位发NC
        for (String chlocation : chlocationSet) {
            String respMsg = callSaleOutNC(saleOut, saleOutBs, chlocation);
            msg += StringUtils.isEmpty(respMsg) ? "" : respMsg;
        }
        return StringUtils.isEmpty(msg) ? JsonResult.success() : JsonResult.error(msg);
    }

    private String callSaleOutNC(KdlSaleOut saleOut, List<KdlSaleOutB> saleOutBs, String chlocation) {
        // 找出要处理的库位 明细
        List<KdlSaleOutB> processList = new ArrayList<>();
        for (KdlSaleOutB saleOutB : saleOutBs) {
            if (chlocation.equals(saleOutB.getCahlocation())) {
                processList.add(saleOutB);
            }
        }
        //检查制单人、审批人是否配置
        String billMaker = getNCUserId("ZTPP",DataSourceType.SINESYS);
        if(StringUtils.isEmpty(billMaker)){
            return "销售订单出库回传ZTPP对应的制单人未配置";
        }

        SaleOut2NC saleOut2NC = new SaleOut2NC();
        List<SaleOut2NC.Sale2NCDetail> details = new ArrayList<>();
        saleOut2NC.setDetailList(details);
        saleOut2NC.setInitid("SaleOut");
        saleOut2NC.setVbillcode(saleOut.getVendorso());
        saleOut2NC.setCcustomerid(saleOut.getCustomername());
        saleOut2NC.setDbilldate(saleOut.getPgidate());
        saleOut2NC.setCwarehouseid(processList.get(0).getVendorissueplant() + chlocation);
        saleOut2NC.setPk_org(CommonConfig.kdlOrgCode);
        saleOut2NC.setBillmaker(billMaker);
        saleOut2NC.setApprover(billMaker);
//        saleOut2NC.setVdef11("");//
//        saleOut2NC.setVdef22("");//
        for (KdlSaleOutB saleOutB : processList) {
            saleOutB.setSyncTime(DateUtils.getTime());
            saleOutB.setStatus("Y");
            SaleOut2NC.Sale2NCDetail detail = saleOut2NC.detailIns();
            detail.setCsourcebillbid(saleOutB.getVendordnlineno());
            detail.setCmaterialvid(saleOutB.getMaterialcode());
            detail.setNnum(saleOutB.getPgiquantity());
            detail.setVbatchcode(CommonUtils.getBatchCode(CommonConfig.kdlOrgCode,saleOutB.getVendorbatch(), saleOutB.getBoxflag()));
            detail.setVlotno(saleOutB.getVendorbatch());
//            detail.setVlotno_dprodate(saleOutB.getManufacturedate());
//            detail.setVlotno_vinvaliddate(saleOutB.getExpireddate());
//            kdlPurchaseinBMapper.getPBByVendorbatch()
            //通过批号取采购订单的生产日期及有效期
            KdlPurchaseinB pb = kdlPurchaseinBMapper.getPBByVendorbatch(saleOutB.getVendorbatch(),saleOutB.getMaterialcode());
            detail.setVlotno_dprodate(pb.getManufacturedate());
            detail.setVlotno_vinvaliddate(pb.getExpireddate());
            detail.setVbatchcode_vdef12(saleOutB.getBoxflag());
            detail.setVbatchcode_vdef16(saleOutB.getBoxno());
            String cstateid = getStockStatus(saleOutB.getCahissueplant(),chlocation);
            detail.setCstateid(cstateid);
            details.add(detail);
        }
        String body = JSON.toJSONString(saleOut2NC);
        JsonResult result = sendToReviewLog.callEsbKdl("SaleOut", saleOut.getVendorso(), body);
        if (StringUtils.isEmpty(result.getMsg())) {
            processList.forEach(kdlSaleOutBMapper::updateById);
            saleOut.setStatus(StringUtils.isEmpty(saleOut.getStatus()) ? null : saleOut.getStatus() + "Y");
            kdlSaleOutMapper.updateById(saleOut);
        }
        return result.getMsg();
    }

    /*
     * 康德乐销售出库质检回传记录回写NC
     * */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitSaleOutQCToNC(Integer id) {
        try {
            StringBuilder resultMsgSb = new StringBuilder();
            KdlSaleOutQc qc = kdlSaleOutQcMapper.selectById(id);
            String billMaker = getNCUserId("ZTPP", DataSourceType.SINESYS);
            List<KdlSaleOutQc> qcList = kdlSaleOutQcMapper.selectList(new QueryWrapper<KdlSaleOutQc>().eq("vendorso", qc.getVendorso()).eq("status","N").eq("inspectionlot",qc.getInspectionlot()).ne("inspectionresult","取消"));

            //分库位推送
            String vbatchcode="";
            List<String> storeLocationCheckList = new ArrayList<>();
            StringBuilder stringBuilder = new StringBuilder();
            String[] batchList = new String[3];
            String pk_order_b = "";
            String scmBatchCode = "";
            String vlotno = "";
            //String switchCode = this.getDicStatus("SWITCH", "SWITCH_STORE", DataSourceType.SINESYS);
            NcServiceLog ncServiceLog = new NcServiceLog();
            for (KdlSaleOutQc item: qcList ) {
                pk_order_b = item.getVendordnlineno();
                String chlocation = kdlSaleOutQcMapper.getChlocation(pk_order_b);
                //根据销售订单明细主键获取NC 批次号、箱型、箱号，三个数据以逗号分隔
                scmBatchCode = kdlSaleOutQcMapper.getSCMBatchcode(pk_order_b);
                if(StringUtils.isEmpty(scmBatchCode) || StringUtils.isEmpty(scmBatchCode.split(",",-1)[0])){
                    log.info("康德乐回传的销退订单明细主键:"+pk_order_b+"在NC中未找到对应的批次号信息");
                    stringBuilder.append("康德乐回传的销退订单明细主键:"+pk_order_b+"在NC中未找到对应的批次号信息");
                    if(storeLocationCheckList.contains(chlocation)) {
                        storeLocationCheckList.remove(chlocation);
                    }
                    continue;
                }
                //根据销售订单明细主键获取NC 批号
                vlotno = kdlSaleOutQcMapper.getNCVlotno(pk_order_b);
                //还原批次号、箱型、箱号，生成3个元素的数组
                batchList = scmBatchCode.split(",",-1);
                if(StringUtils.isEmpty(batchList[0])){
                    //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
                    //stringBuilder.append("康德乐回传的销退订单明细主键:"+pk_order_b+"在NC中未找到对应的批次号信息");
                    //若批次号为空，则之前验证合格的仓库需要删除
                    if(storeLocationCheckList.contains(chlocation)) {
                        storeLocationCheckList.remove(chlocation);
                    }
                }else{
                        //康德乐回传的批号、箱型、箱号与NC订单中的一致，允许回写NC
                        if(item.getVendorbatch().equals(vlotno) && item.getBoxflag().equals(batchList[1]) && item.getBoxno().equals(batchList[2])) {
                            if(!storeLocationCheckList.contains(chlocation)) {
                                storeLocationCheckList.add(chlocation);
                            }
                        }else{
                            log.info("销售批号信息校验异常：实物【"+item.getComdescription()+"】的批号、箱型、箱号【"+item.getVendorbatch()+"、"+item.getBoxflag()+"、"+item.getBoxno()+"】批号相关信息同订单指令【"+vlotno+"、"+batchList[1]+"、"+batchList[2]+"】不一致");
                            stringBuilder.append("销售批号信息校验异常：实物【"+item.getComdescription()+"】的批号、箱型、箱号【"+item.getVendorbatch()+"、"+item.getBoxflag()+"、"+item.getBoxno()+"】批号相关信息同订单指令【"+vlotno+"、"+batchList[1]+"、"+batchList[2]+"】不一致");
                            if(storeLocationCheckList.contains(chlocation)) {
                                storeLocationCheckList.remove(chlocation);
                            }
                        }
                }

            }
            if(stringBuilder.toString().length()>0){
                ncServiceLog.setSubmitNo(qc.getVendorso()+"_SaleOut");
                ncServiceLog.setRequestBody("");
                ncServiceLog.setSubmitTime(DateUtils.now());
                ncServiceLog.setResponseBody(stringBuilder.toString());
                ncServiceLog.setResponseCode("500");
                ncServiceLog.setResponseResult("");
                String dataSource = DynamicDataSource.getDataSource();
                DynamicDataSource.setDataSource(DataSourceType.MASTER.getName());
                ncServiceLogService.save(ncServiceLog);
                DynamicDataSource.setDataSource(dataSource);
                return JsonResult.error(stringBuilder.toString());
            }
            HashMap<String, List<KdlSaleOutQc>> map = new HashMap<>();
            for (KdlSaleOutQc saleOutQc : qcList) {
                String vendordnlineno = saleOutQc.getVendordnlineno();
                //根据明细主键查库位
                String chlocation = kdlSaleOutQcMapper.getChlocation(vendordnlineno);
                //如果库位在检验通过列表中存在，则运行回写NC
                if(storeLocationCheckList.contains(chlocation)) {
                    if (!map.containsKey(chlocation)) {
                        List<KdlSaleOutQc> list = new ArrayList<>();
                        list.add(saleOutQc);
                        map.put(chlocation, list);
                    } else {
                        List<KdlSaleOutQc> processList = map.get(chlocation);
                        processList.add(saleOutQc);
                    }
                }
            }
            //若没有检验通过的数据，则返回错误提示
            if(map.size()==0){
                return JsonResult.error(stringBuilder.toString());
            }

            String[] finalBatchList = batchList;
            map.forEach((chlocation, processList) -> {
                SaleOut2NC saleOut2NC = new SaleOut2NC();

                List<SaleOut2NC.Sale2NCDetail> details = new ArrayList<>();
                saleOut2NC.setDetailList(details);
                saleOut2NC.setInitid("SaleOut");
                saleOut2NC.setVbillcode(chlocation+qc.getInspectionlot());
                saleOut2NC.setCcustomerid(qc.getCustomername());
//                saleOut2NC.setDbilldate(qc.getGidate());
                saleOut2NC.setDbilldate(qc.getInspectiondate1());
                saleOut2NC.setCwarehouseid(qc.getVendorplant() + chlocation);
                saleOut2NC.setPk_org(qc.getCompanycode());
                saleOut2NC.setBillmaker(billMaker);
                saleOut2NC.setApprover(billMaker);
                for (KdlSaleOutQc saleOutQc : processList) {
                    saleOutQc.setStatus("Y");
                    SaleOut2NC.Sale2NCDetail detail = saleOut2NC.detailIns();
                    detail.setCsourcebillbid(saleOutQc.getVendordnlineno());
                    detail.setCmaterialvid(saleOutQc.getMaterialcode());
                    detail.setNnum(saleOutQc.getGiquantity());
                    detail.setVbatchcode(kdlSaleOutQcMapper.getSOBatchcode(saleOutQc.getVendordnlineno()));
                    detail.setVlotno(saleOutQc.getVendorbatch());
                    //通过批号取采购订单的生产日期及有效期
                    KdlPurchaseinB pb = kdlPurchaseinBMapper.getPBByVendorbatch(saleOutQc.getVendorbatch(),saleOutQc.getMaterialcode());
                    detail.setVlotno_dprodate(pb.getManufacturedate());
                    detail.setVlotno_vinvaliddate(pb.getExpireddate());
                    detail.setVbatchcode_vdef12(saleOutQc.getBoxflag());
                    detail.setVbatchcode_vdef16(saleOutQc.getBoxno());
                    String cstateid = getStockStatus(saleOutQc.getVendorplant(), chlocation);
                    detail.setCstateid(cstateid);
                    details.add(detail);
                }
                String body = JSON.toJSONString(saleOut2NC);
                JsonResult result = sendToReviewLog.callEsbKdl("SaleOut", qc.getVendorso()+chlocation+"_"+qc.getInspectionlot(), body);
                if ("操作成功".equals(result.getMsg())) {
                    processList.forEach(kdlSaleOutQcMapper::updateById);
                }
            });
            return JsonResult.success(resultMsgSb.toString());
        } catch (Exception ex) {
            return JsonResult.error(ex.getMessage()==null?"操作失败":ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitSaleOutQCToNC(String vendorso) {
        try {
            StringBuilder resultMsgSb = new StringBuilder();
            String billMaker = getNCUserId("ZTPP", DataSourceType.SINESYS);
            List<KdlSaleOutQc> qcList = kdlSaleOutQcMapper.selectList(new QueryWrapper<KdlSaleOutQc>().eq("vendorso", vendorso).eq("mark",1).ne("inspectionresult","取消"));
            if(qcList.size()==0){
                return JsonResult.error("销售订单："+vendorso+"没有对应的销售出库明细");
            }
            AtomicReference<KdlSaleOutQc> qc = new AtomicReference<>(qcList.get(0));
            //分库位推送
            String vbatchcode="";
            List<String> storeLocationCheckList = new ArrayList<>();
            StringBuilder stringBuilder = new StringBuilder();
            String[] batchList = new String[3];
            String pk_order_b = "";
            String scmBatchCode = "";
            String vlotno = "";
            boolean checkFlag = true;
            String switchCode = this.getDicStatus("SWITCH", "SWITCH_STORE", DataSourceType.SINESYS);
            checkFlag = switchCode.equals("1")?true:false;
            if(checkFlag) {
                NcServiceLog ncServiceLog = new NcServiceLog();
                for (KdlSaleOutQc item : qcList) {
                    pk_order_b = item.getVendordnlineno();
                    String chlocation = kdlSaleOutQcMapper.getChlocation(pk_order_b);
                    //根据销售订单明细主键获取NC 批次号、箱型、箱号，三个数据以逗号分隔
                    scmBatchCode = kdlSaleOutQcMapper.getSCMBatchcode(pk_order_b);
                    if (StringUtils.isEmpty(scmBatchCode) || StringUtils.isEmpty(scmBatchCode.split(",", -1)[0])) {
                        log.info("康德乐回传的销退订单明细主键:" + pk_order_b + "在NC中未找到对应的批次号信息");
                        stringBuilder.append("康德乐回传的销退订单明细主键:" + pk_order_b + "在NC中未找到对应的批次号信息<br/>");
                        if (storeLocationCheckList.contains(chlocation)) {
                            storeLocationCheckList.remove(chlocation);
                        }
                        continue;
                    }
                    //根据销售订单明细主键获取NC 批号
                    vlotno = kdlSaleOutQcMapper.getNCVlotno(pk_order_b);
                    //还原批次号、箱型、箱号，生成3个元素的数组
                    batchList = scmBatchCode.split(",", -1);
                    if (StringUtils.isEmpty(batchList[0])) {
                        //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
                        //stringBuilder.append("康德乐回传的销退订单明细主键:"+pk_order_b+"在NC中未找到对应的批次号信息");
                        //若批次号为空，则之前验证合格的仓库需要删除
                        if (storeLocationCheckList.contains(chlocation)) {
                            storeLocationCheckList.remove(chlocation);
                        }
                    } else {
                        //康德乐回传的批号、箱型、箱号与NC订单中的一致，允许回写NC
                        if (item.getVendorbatch().equals(vlotno) && item.getBoxflag().equals(batchList[1]) && item.getBoxno().equals(batchList[2])) {
                            if (!storeLocationCheckList.contains(chlocation)) {
                                storeLocationCheckList.add(chlocation);
                            }
                        } else {
                            log.info("销售批号信息校验异常：实物【" + item.getComdescription() + "】的批号、箱型、箱号【" + item.getVendorbatch() + "、" + item.getBoxflag() + "、" + item.getBoxno() + "】批号相关信息同订单指令【" + vlotno + "、" + batchList[1] + "、" + batchList[2] + "】不一致");
                            stringBuilder.append("销售批号信息校验异常：实物【" + item.getComdescription() + "】的批号、箱型、箱号【" + item.getVendorbatch() + "、" + item.getBoxflag() + "、" + item.getBoxno() + "】批号相关信息同订单指令【" + vlotno + "、" + batchList[1] + "、" + batchList[2] + "】不一致");
                            if (storeLocationCheckList.contains(chlocation)) {
                                storeLocationCheckList.remove(chlocation);
                            }
                        }
                    }

                }
                if (stringBuilder.toString().length() > 0) {
                    ncServiceLog.setSubmitNo(vendorso + "_SaleOut");
                    ncServiceLog.setRequestBody("");
                    ncServiceLog.setSubmitTime(DateUtils.now());
                    ncServiceLog.setResponseBody(stringBuilder.toString());
                    ncServiceLog.setResponseCode("500");
                    ncServiceLog.setResponseResult("");
                    String dataSource = DynamicDataSource.getDataSource();
                    DynamicDataSource.setDataSource(DataSourceType.MASTER.getName());
                    ncServiceLogService.save(ncServiceLog);
                    DynamicDataSource.setDataSource(dataSource);
                    return JsonResult.error(stringBuilder.toString());
                }
            }
            HashMap<String, List<KdlSaleOutQc>> map = new HashMap<>();
            String mapKey = "";
            for (KdlSaleOutQc saleOutQc : qcList) {
                String vendordnlineno = saleOutQc.getVendordnlineno();
                //根据明细主键查库位
                String chlocation = kdlSaleOutQcMapper.getChlocation(vendordnlineno);
                storeLocationCheckList.add(chlocation);
                mapKey = chlocation+"_"+saleOutQc.getInspectionlot();
                //如果库位在检验通过列表中存在，则运行回写NC
                if(storeLocationCheckList.contains(chlocation)) {
                    if (!map.containsKey(mapKey)) {
                        List<KdlSaleOutQc> list = new ArrayList<>();
                        list.add(saleOutQc);
                        map.put(mapKey, list);
                    } else {
                        List<KdlSaleOutQc> processList = map.get(mapKey);
                        processList.add(saleOutQc);
                    }
                }
            }
            //若没有检验通过的数据，则返回错误提示
            if(map.size()==0){
                return JsonResult.error(stringBuilder.toString());
            }

            //String[] finalBatchList = batchList;
            map.forEach((chlocation, processList) -> {
                SaleOut2NC saleOut2NC = new SaleOut2NC();
                qc.set(processList.get(0));
                List<SaleOut2NC.Sale2NCDetail> details = new ArrayList<>();
                saleOut2NC.setDetailList(details);
                saleOut2NC.setInitid("SaleOut");
                saleOut2NC.setVbillcode(chlocation.split("_")[0]+ qc.get().getInspectionlot());
                saleOut2NC.setCcustomerid(qc.get().getCustomername());
//                saleOut2NC.setDbilldate(qc.getGidate());
                //单据日期取质检日期 2024-06-17
                saleOut2NC.setDbilldate(qc.get().getInspectiondate1());
                saleOut2NC.setCwarehouseid(qc.get().getVendorplant() + chlocation.split("_")[0]);
                saleOut2NC.setPk_org(qc.get().getCompanycode());
                saleOut2NC.setBillmaker(billMaker);
                saleOut2NC.setApprover(billMaker);
                for (KdlSaleOutQc saleOutQc : processList) {
                    saleOutQc.setStatus("Y");
                    SaleOut2NC.Sale2NCDetail detail = saleOut2NC.detailIns();
                    detail.setCsourcebillbid(saleOutQc.getVendordnlineno());
                    detail.setCmaterialvid(saleOutQc.getMaterialcode());
                    detail.setNnum(saleOutQc.getGiquantity());
                    detail.setVbatchcode(kdlSaleOutQcMapper.getSOBatchcode(saleOutQc.getVendordnlineno()));
                    detail.setVlotno(saleOutQc.getVendorbatch());
                    //通过批号取采购订单的生产日期及有效期
                    KdlPurchaseinB pb = kdlPurchaseinBMapper.getPBByVendorbatch(saleOutQc.getVendorbatch(),saleOutQc.getMaterialcode());
                    if(pb!=null) {
                        detail.setVlotno_dprodate(pb.getManufacturedate());
                        detail.setVlotno_vinvaliddate(pb.getExpireddate());
                    }else{
                        detail.setVlotno_dprodate("");
                        detail.setVlotno_vinvaliddate("");
                    }
                    detail.setVbatchcode_vdef12(saleOutQc.getBoxflag());
                    detail.setVbatchcode_vdef16(saleOutQc.getBoxno());
                    String cstateid = getStockStatus(saleOutQc.getVendorplant(), chlocation.split("_")[0]);
                    detail.setCstateid(cstateid);
                    details.add(detail);
                }
                String body = JSON.toJSONString(saleOut2NC);
                JsonResult result = sendToReviewLog.callEsbKdl("SaleOut", qc.get().getVendorso()+chlocation, body);
                if ("操作成功".equals(result.getMsg())) {
                    processList.forEach(kdlSaleOutQcMapper::updateById);
                }
                else{
                    resultMsgSb.append(result.getMsg());
                }
            });
            return resultMsgSb.toString().isEmpty()?JsonResult.success():JsonResult.error(resultMsgSb.toString());
        } catch (Exception ex) {
            return JsonResult.error(ex.getMessage()==null?"操作失败":ex.getMessage());
        }
    }

    /*
     * 康德乐采购退货回传记录回写NC
     * */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitPurchaseReturnToNC(Integer id) {
        String body = "";
        StringBuilder sb = new StringBuilder();
        KdlPurchaseinReturn entity = kdlPurchaseinReturnMapper.selectById(id);
        if(StringUtils.isNull(entity))
        {
            return JsonResult.error("无效的id:"+id.toString());
        }
        //检查制单人、审批人是否配置
        String billMaker = getNCUserId("ZST3",DataSourceType.SINESYS);
        if(StringUtils.isEmpty(billMaker)){
            return JsonResult.error("采购退货出库回传ZST3对应的制单人未配置");
        }
        //检查组织代码
        if(StringUtils.isEmpty(entity.getCompanycode())){
            return JsonResult.error("采购退货出库回传对应的组织代码为空");
        }


        List<KdlPurchaseinReturnB> list = null;

        list = kdlPurchaseinReturnMapper.getPurchaseinReturnDetail(id);
        //采购订单明细主键
        String pk_order_b = "";
        String scmBatchCode = null;
        String vlotno = "";
        NcServiceLog log = new NcServiceLog();
        List<String> storeLocationCheckList = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
        String[] batchList = new String[3];
        for (KdlPurchaseinReturnB item: list ) {
            pk_order_b = item.getVendorpolineno();
            scmBatchCode = kdlPurchaseinReturnMapper.getSCMBatchcode(pk_order_b);
            vlotno = kdlPurchaseinReturnMapper.getNCVlotno(pk_order_b);
            if(StringUtils.isEmpty(scmBatchCode)){
                stringBuilder.append("康德乐回传的采退订单明细主键:" + pk_order_b + "在NC中未找到对应的批次号信息");
            }else {
                batchList = scmBatchCode.split(",", -1);
                if (StringUtils.isEmpty(batchList[0])) {
                    //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
                    stringBuilder.append("康德乐回传的采退订单明细主键:" + pk_order_b + "在NC中未找到对应的批次号信息");
                    if (storeLocationCheckList.contains(item.getCahlocation())) {
                        storeLocationCheckList.remove(item.getCahlocation());
                    }
                } else {
                    String switchCode = this.getDicStatus("SWITCH", "SWITCH_P_R", DataSourceType.SINESYS);
                    if (switchCode.equals("0")) {
                        if (!storeLocationCheckList.contains(item.getCahlocation())) {
                            storeLocationCheckList.add(item.getCahlocation());
                        }
                    }else {
                        //康德乐回传的批号、箱型、箱号与NC订单中的一致，允许回写NC
                        if (item.getVendorbatch().equals(vlotno) && item.getBoxflag().equals(batchList[1]) && item.getBoxno().equals(batchList[2])) {
                            if (!storeLocationCheckList.contains(item.getCahlocation())) {
                                storeLocationCheckList.add(item.getCahlocation());
                            }
                        } else {
                            stringBuilder.append("采退批号信息校验异常：实物【" + item.getComdescription() + "】的批号、箱型、箱号【" + item.getVendorbatch() + "、" + item.getBoxflag() + "、" + item.getBoxno() + "】批号相关信息同订单指令【" + vlotno + "、" + batchList[1] + "、" + batchList[2] + "】不一致");
                            if (storeLocationCheckList.contains(item.getCahlocation())) {
                                storeLocationCheckList.remove(item.getCahlocation());
                            }
                        }
                    }
                }
            }

        }
        if(stringBuilder.toString().length()>0){
            log.setSubmitNo(entity.getVendorpo()+"_PurchaseIn");
            log.setRequestBody("");
            log.setSubmitTime(DateUtils.now());
            log.setResponseBody(stringBuilder.toString());
            log.setResponseCode("500");
            log.setResponseResult("");
            String dataSource = DynamicDataSource.getDataSource();
            DynamicDataSource.setDataSource(DataSourceType.MASTER.getName());
            ncServiceLogService.save(log);
            DynamicDataSource.setDataSource(dataSource);
            return JsonResult.error(stringBuilder.toString());
        }

        //获取库位列表
        List<String> storeLocationList = kdlPurchaseinReturnMapper.getStorageLocation(entity.getId());
        storeLocationList.retainAll(storeLocationCheckList);
        if(storeLocationList.size()==0){
            return JsonResult.error(stringBuilder.toString());
        }
        NCPurchaseIn ncPurchaseIn = null;
        PurchaseInBodys bodys = null;
        String batchcode="";
        List<PurchaseInBodys> bodysList = new ArrayList<>();
        for (int j = 0; j < storeLocationList.size(); j++) {
            bodysList.clear();
            list = kdlPurchaseinReturnMapper.getPurchaseinReturnNCDetail(entity.getId(),storeLocationList.get(j));
            ncPurchaseIn = new NCPurchaseIn();
            ncPurchaseIn.setInitid("PurchaseIn");
            ncPurchaseIn.setPk_org(entity.getCompanycode());
            ncPurchaseIn.setDbilldate(entity.getPgidate());
            ncPurchaseIn.setVbillcode(storeLocationList.get(j)+list.get(0).getCahdnno());
            //ncPurchaseIn.setVbillcode("1528CD24049022");
            ncPurchaseIn.setCvendorid(entity.getCustomername());
            ncPurchaseIn.setApprover(billMaker);
            ncPurchaseIn.setBillmaker(billMaker);
            for (int i = 0; i < list.size(); i++) {
                bodys = new PurchaseInBodys();
                scmBatchCode = kdlPurchaseinReturnMapper.getSCMBatchcode(list.get(i).getVendorpolineno());
                batchList = scmBatchCode.split(",",-1);
                ncPurchaseIn.setCwarehouseid(list.get(i).getCahissueplant()+storeLocationList.get(j));
                bodys.setCfirstbillbid(list.get(i).getVendorpolineno());
                bodys.setCmaterialvid(list.get(i).getMaterialcode());
                bodys.setNnum(new BigDecimal(list.get(i).getPgiquantity()).negate());
                bodys.setCstateid(list.get(i).getStockstatus()); //NC是否必填
                bodys.setVlotno(list.get(i).getVendorbatch());
                bodys.setVlotno_dprodate(list.get(i).getManufacturedate());
                bodys.setVlotno_vinvaliddate(list.get(i).getExpireddate());
                //batchcode = CommonUtils.getBatchCode(entity.getCompanycode(),list.get(i).getVendorbatch(),list.get(i).getBoxflag());
                batchcode = batchList[0];
                bodys.setVbatchcode(batchcode);
                bodys.setVbatchcode_vdef3("");
                bodys.setVbatchcode_vdef15("");
                bodys.setVbatchcode_vdef12(list.get(i).getBoxflag());
                bodys.setVbatchcode_vdef16(list.get(i).getBoxno());
                bodysList.add(bodys);
            }
            ncPurchaseIn.setBodys(bodysList);
            body = JSON.toJSONString(ncPurchaseIn);
            JsonResult result = sendToReviewLog.callEsbKdl("PurchaseIn", entity.getVendorpo() + "_" + ncPurchaseIn.getCwarehouseid(), body);
            if (result.getCode() > 0) {
                sb.append(result.getMsg());
            }
            else{
                //更新回写状态
                DynamicDataSource.setDataSource("sinesys");
                UpdateWrapper<KdlPurchaseinReturnB> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("status", Constants.NC_SUBMIT_STATUS).eq("pid",entity.getId()).eq("cahlocation",storeLocationList.get(j));
                kdlPurchaseinReturnBMapper.update(new KdlPurchaseinReturnB(),updateWrapper);
            }
        }
        return StringUtils.isEmpty(sb.toString())?JsonResult.success():JsonResult.error(sb.toString());
    }


    /**
     * 根据工厂及仓库代码获取库存状态
     * @param plant 工厂代码
     * @param warehouseid 仓库代码
     * @return 库存状态
     */
    private String getStockStatus(String plant,String warehouseid){
        KdlStoredoc storedoc = kdlStoredocMapper.selectOne(new QueryWrapper<KdlStoredoc>().eq("plant",plant).eq("bincode",warehouseid));
        if(StringUtils.isNull(storedoc)){
            return "";
        }
        return storedoc.getStockstatus();
    }

    /**
     * 根据移库结果记录的id判读是否为采购来源的异常反馈移库
     * @param id
     * @return
     */
    private boolean isPurchaseFeedback(String id){
        List<KdlGM> gmList= kdlGMMapper.getPurchaseFeedback(id);
        return gmList.size()>0?true:false;
    }
    /**
     * 根据移库结果记录的id判读是否为销售来源的异常反馈移库
     * @param id
     * @return
     */
    private boolean isSaleFeedback(String id){
        List<KdlGM> gmList= kdlGMMapper.getSaleFeedback(id);
        return gmList.size()>0?true:false;
    }

    /**
     * 根据批号获取采购入库质检回传中对应批号的生产日期和有效日期
     * @param vlotno
     * @return
     */
    private BatchCodeDate getBatchCodeDate(String materialcode,String vlotno){
        BatchCodeDate batchCodeDate = new BatchCodeDate();
        KdlPurchaseinB entity= kdlPurchaseinBMapper.getPBByVendorbatch(vlotno,materialcode);
        if(StringUtils.isNull(entity)){
            return null;
        }
        batchCodeDate.setManufacturedate(entity.getManufacturedate());
        batchCodeDate.setExpireddate(entity.getExpireddate());
        return batchCodeDate;
    }
    /*
     * 康德乐移库记录回写NC
     * */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitWhstransToNC(String orderno) {
        return submitWhstransToNCT(orderno,false);
    }

    /*
     * 康德乐移库记录回写NC
     * */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitWhstransToNCT(String orderno,Boolean withT) {
        String body = "";
        StringBuilder sb = new StringBuilder();
        // 获取数据列表
        Map<String,Object> paramOrder = new HashMap<>();
        paramOrder.put("orderno",orderno);
        List<KdlGM> entityList = kdlGMMapper.selectByMap(paramOrder);
        if(entityList.size()==0)
        {
            return JsonResult.error("无效的物料凭证号:"+orderno);
        }
        KdlGM entity = entityList.get(0);
        //若组织编码为空，则提示需要人工干预匹配组织后上传
        if(StringUtils.isEmpty(entity.getCompanycode())){
            return JsonResult.error("组织代码为空，请根据药品编码、批号更新相应的组织后上传。");
        }

        //检查制单人、审批人是否配置
        String billMaker = getNCUserId("GM",DataSourceType.SINESYS);
        if(StringUtils.isEmpty(billMaker)){
            return JsonResult.error("移库回传对应的制单人未配置");
        }

        //如果是信谊的指令移库，检查移库结果中的仓库、批号、箱号、箱型是否通NC订单一致
        String batchcode="";
        String pk_order_b="";
        String vlotno = "";
        NcServiceLog ncServiceLog = new NcServiceLog();


        //NCWhstrans ncWhstrans = null;

        batchcode="";
        String cstateid = getStockStatus(entity.getPlant(),entity.getFromlocation());
        if(StringUtils.isEmpty(cstateid)){
            return JsonResult.error("工厂:"+entity.getPlant()+"仓库:"+entity.getFromlocation()+"不存在对应的库存状态");
        }
        //如果是信谊发起指令的移库，采购和销退对应的移库不走移库接口
        if(!StringUtils.isEmpty(entity.getPrincipalorderno())&&!StringUtils.startsWith(entity.getPrincipalorderno(),"YK")) {
            //根据移库的异常反馈指令获取采购/销售订单号
            String vbillcode = kdlGMMapper.getNCOrderno(orderno);
            if (StringUtils.isEmpty(vbillcode)) {
                return JsonResult.error("QFF异常反馈信息错误：NC单据号为空");
            } else {
                //如果是销售订单
                Map<String, Object> param = new HashMap<>();
                if (vbillcode.toUpperCase().contains("SO")) {
                    param.put("vendorso", vbillcode);
                    if (kdlZ05kdlMapper.selectByMap(param).size() == 0) {
                        return JsonResult.error("QFF异常反馈对应的销退质检回传不存在");
                    }
                } else {
                    //处理采购订单
                    param.put("vendorpo", vbillcode);
                    if (CollectionUtils.isEmpty(kdlPurchaseinMapper.selectByMap(param))) {
                        return JsonResult.error("QFF异常反馈对应的采购入库质检回传不存在");
                    }
                }
            }
            //判断是否整箱拆零的情况
            if (!entity.getBoxflag().equals(entity.getBoxflagto())) {
                //整箱拆零的情况，根据移库数据先调用其他出库，再调用其他入库接口
                if (entity.getInoutstep().equals(1)) {
                    JsonResult ret = submitGeneralInToNC(orderno, true);
                    if (ret.getCode() == 0) {
                        //更新 inoutstep=2,标记其他入库已回写成功
                        kdlGMService.updateInoutStep(orderno, 2);
                    }
                    return ret;
                } else {
                    JsonResult res1 = submitGeneralOutToNC(orderno, false);
                    if (res1.getCode() == 0) {
                        //更新 inoutstep=1,标记其他出库已回写成功
                        kdlGMService.updateInoutStep(orderno, 1);
                        DynamicDataSource.setDataSource("sinesys");
                        JsonResult ret2 = submitGeneralInToNC(orderno, true);
                        if (ret2.getCode() == 0) {
                            //更新 inoutstep=2,标记其他入库已回写成功
                            kdlGMService.updateInoutStep(orderno, 2);
                        }
                        return ret2;
                    } else {
                        return res1;
                    }
                }
            } else {
                //判断移库结果是否为采购来源的异常反馈结果,且fromlocation是1012
                if (isPurchaseFeedback(orderno)) {
                    if ("1012".equals(entity.getFromlocation())) {
                        log.info("移库结果是采购订单的异常反馈，不回写NC移库接口,回写采购入库接口");
                        //return JsonResult.error("移库结果是采购订单的异常反馈，不回写NC移库接口,回写采购入库接口");
                        return submitFeedbackInspectToNC(orderno);
                    }
                    //采购对应的那笔待检状态改成 已回写 和 库位改成最新库位
                } else {
                    if (isSaleFeedback(orderno)) {
                        log.info("移库结果是销退订单的异常反馈，不回写NC移库接口,回写销退入库接口");
                        //return JsonResult.error("移库结果是销退订单的异常反馈，不回写NC移库接口,回写销退入库接口");
                        return submitFeedbackSaleReturnToNC(orderno);
                        //销售对应的那笔待检状态改成 已回写 和 库位改成最新库位
                    }
                }
            }
        }

        //判断是否整箱拆零的情况
        if(!entity.getBoxflag().equals(entity.getBoxflagto())) {
            //整箱拆零的情况，根据移库数据先调用其他出库，再调用其他入库接口
            if(entity.getInoutstep().equals(1)){
                JsonResult ret= submitGeneralInToNC(orderno, true);
                if (ret.getCode() == 0) {
                    //更新 inoutstep=2,标记其他入库已回写成功
                    kdlGMService.updateInoutStep(orderno, 2);
                }
                return  ret;
            }else {
                JsonResult res1 = submitGeneralOutToNC(orderno, false);
                if (res1.getCode() == 0) {
                    //更新 inoutstep=1,标记其他出库已回写成功
                    kdlGMService.updateInoutStep(orderno,1);
                    DynamicDataSource.setDataSource("sinesys");
                    JsonResult ret2= submitGeneralInToNC(orderno, true);
                    if (ret2.getCode() == 0) {
                        //更新 inoutstep=2,标记其他入库已回写成功
                        kdlGMService.updateInoutStep(orderno, 2);
                    }
                    return ret2;
                } else {
                    return res1;
                }
            }
        }
        List<WhstransBodys> bodysList = new ArrayList<>();
        //获取物料凭证对应的组织代码
        List<KdlGMVo> companyList = kdlGMMapper.getGMCompanyList(orderno);
        for (KdlGMVo gmVo:companyList) {
            bodysList.clear();
            List<KdlGMVo> detailList = kdlGMMapper.getCompanyGMDetailList(entity.getOrderno(),gmVo.getCompanycode(),gmVo.getFromlocation(),gmVo.getTolocation());
            NCWhstrans ncWhstrans = new NCWhstrans();
            ncWhstrans.setInitid("Whstrans");
            ncWhstrans.setPk_org(entity.getCompanycode());
            ncWhstrans.setCtrantypeid("4K-Cxx-1183-01");
            ncWhstrans.setVbillcode(entity.getCompanycode() + entity.getOrderno());
            ncWhstrans.setDbilldate(entity.getOrderdate());
            ncWhstrans.setApprover(billMaker);
            ncWhstrans.setBillmaker(billMaker);
            ncWhstrans.setCbizid(billMaker);
//            //待验库不入NC
//            if ("1012".equals(entity.getFromlocation()) || "1012".equals(entity.getTolocation())) {
//                continue;
//            }
            ncWhstrans.setCwarehouseid(entity.getPlant() + entity.getFromlocation());
            ncWhstrans.setCotherwhid(entity.getPlant() + entity.getTolocation());
            for (KdlGMVo item : detailList) {
                ncWhstrans.setVbillcode(item.getCompanycode() + item.getFromlocation()+item.getTolocation()+item.getOrderno());
                ncWhstrans.setCwarehouseid(item.getPlant() + item.getFromlocation());
                ncWhstrans.setCotherwhid(item.getPlant() + item.getTolocation());
                WhstransBodys bodys = new WhstransBodys();
                bodys.setCmaterialvid(item.getItemno());
                bodys.setNassistnum(item.getQty());
                bodys.setCstateid(cstateid);
                bodys.setCphh(item.getVendorbatch());
                bodys.setCphh2(item.getVendorbatch());

                if (!StringUtils.isEmpty(item.getNcbatch())) {
                    bodys.setPk_batchcode(item.getNcbatch());
                    bodys.setPk_batchcode2(item.getNcbatch());
                } else {
                    String switchCode = this.getDicStatus("SWITCH", "SAP_BATCHNO", DataSourceType.SINESYS);
                    if(switchCode.equals("1")) {
                        bodys.setPk_batchcode(CommonUtils.getBatchCode(item.getCompanycode(), item.getVendorbatch(), item.getBoxflag(), item.getBatchno()));
                        bodys.setPk_batchcode2(CommonUtils.getBatchCode(item.getCompanycode(), item.getVendorbatch(), item.getBoxflagto(), item.getBatchnoto()));
                    }else {
                        bodys.setPk_batchcode(CommonUtils.getBatchCode(item.getCompanycode(), item.getVendorbatch(), item.getBoxflag(), ""));
                        bodys.setPk_batchcode2(CommonUtils.getBatchCode(item.getCompanycode(), item.getVendorbatch(), item.getBoxflagto(), ""));
                    }
                }
                BatchCodeDate codeDate = getBatchCodeDate(item.getItemno(), item.getVendorbatch());
                if (StringUtils.isNull(codeDate)) {
                    return JsonResult.error("采购入库质检回传中不存在对应的生产批号：" + entity.getVendorbatch());
                }
                bodys.setRkkczt(getStockStatus(item.getPlant(), item.getTolocation()));
                bodys.setDproducedate(codeDate.getManufacturedate());
                bodys.setYxqz(codeDate.getExpireddate());
                bodys.setDproducedate2(codeDate.getManufacturedate());
                bodys.setYxqz2(codeDate.getExpireddate());
                bodys.setVbatchcode_vdef11(item.getBatchnoto());
                bodys.setVbatchcode_vdef12(item.getBoxflagto());
                bodys.setVbatchcode_vdef16(item.getBoxnoto());
                //如果是退货回来的批次号，需要加上T
                if (withT){
                    bodys.setPk_batchcode2("T"+bodys.getPk_batchcode2());
                    bodys.setPk_batchcode("T"+bodys.getPk_batchcode());
                }

//            bodys.set(entity.getBatchno());
//            bodys.setVlotno_dprodate(list.get(i).getVlotnoDprodate());
//            bodys.setVlotno_vinvaliddate(list.get(i).getVlotnoVinvaliddate());
//            batchcode = CommonConfig.kdlOrgCode+list.get(i).getVlotno()+list.get(i).getBoxflag();
//            bodys.setVbatchcode(batchcode);
//            bodys.setVbatchcode_vdef3("");
//            bodys.setVbatchcode_vdef15("");
//            bodys.setVbatchcode_vdef16(list.get(i).getBoxno());
                bodysList.add(bodys);
            }
            //如果是退货回来的批次号，需要加上T
            if (withT){
                ncWhstrans.setVbillcode(ncWhstrans.getVbillcode()+"1");
            }
            ncWhstrans.setDetailList(bodysList);
            body = JSON.toJSONString(ncWhstrans);
            JsonResult result = sendToReviewLog.callEsbKdl(ncWhstrans.getInitid(), gmVo.getCompanycode()+gmVo.getOrderno() + "_" + gmVo.getFromlocation() + "_" + gmVo.getTolocation(), body);
            if (result.getCode() > 0) {
                sb.append(result.getMsg());
            } else {
                DynamicDataSource.setDataSource("sinesys");
                UpdateWrapper<KdlGM> updateWrapper = new UpdateWrapper<>();
                //根据单号、事业部、转出库位、转入库位更新回写状态
                updateWrapper.set("status", Constants.NC_SUBMIT_STATUS).eq("orderno", gmVo.getOrderno()).eq("companycode", gmVo.getCompanycode()).eq("fromlocation", gmVo.getFromlocation()).eq("tolocation", gmVo.getTolocation());
                //entity.setStatus(Constants.NC_SUBMIT_STATUS);
                kdlGMMapper.update(new KdlGM(), updateWrapper);
            }
        }
        return StringUtils.isEmpty(sb.toString())?JsonResult.success():JsonResult.error(sb.toString());
    }

    /*
     * 康德乐其他出出库回传记录回写NC
     * */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitGeneralOutToNC(String orderno,boolean updateStatus) {
        String body = "";
        StringBuilder sb = new StringBuilder();
        Map<String,Object> paramOrder = new HashMap<>();
        paramOrder.put("orderno",orderno);
        List<KdlGM> entityList = kdlGMMapper.selectByMap(paramOrder);
        if(entityList.size()==0)
        {
            return JsonResult.error("无效的物料凭证号:"+orderno);
        }
        KdlGM entity = entityList.get(0);
        //检查制单人、审批人是否配置
        String billMaker = getNCUserId("GM",DataSourceType.SINESYS);
        if(StringUtils.isEmpty(billMaker)){
            return JsonResult.error("其他出库回传对应的制单人未配置");
        }
        String batchcode="";
        //检查仓库库存状态是否配置
        String cstateid = getStockStatus(entity.getPlant(),entity.getFromlocation());
        if(StringUtils.isEmpty(cstateid)){
            return JsonResult.error("工厂:"+entity.getPlant()+"仓库:"+entity.getFromlocation()+"不存在对应的库存状态");
        }
        //检查批号是否有效
        BatchCodeDate codeDate = getBatchCodeDate(entity.getItemno(),entity.getVendorbatch());
        if(StringUtils.isNull(codeDate)){
            return JsonResult.error("采购入库质检回传中不存在对应的生产批号："+entity.getVendorbatch());
        }

        List<GeneralOutBodys> bodysList = new ArrayList<>();
        List<KdlGMVo> companyList = kdlGMMapper.getOtherOutCompanyList(orderno);
        for (KdlGMVo gmVo:companyList) {
            bodysList.clear();
            NCGeneralOut ncOut = new NCGeneralOut();
            ncOut.setInitid("GeneralOut");
            ncOut.setVbillcode(gmVo.getOrderno());
            ncOut.setDbilldate(entity.getOrderdate());
            ncOut.setCtrantypeid("4I-Cxx-1528-03");
            ncOut.setVnote("");
            ncOut.setCwarehouseid(gmVo.getPlant() + gmVo.getFromlocation());
            ncOut.setPk_org(CommonConfig.kdlOrgCode);
            ncOut.setBillmaker(billMaker);
            ncOut.setApprover(billMaker);
            ncOut.setCbizid(billMaker);
            List<KdlGMVo> detailList = kdlGMMapper.getCompanyGMOtherOutDetailList(entity.getOrderno(),gmVo.getCompanycode(),gmVo.getFromlocation());
            for (KdlGMVo item : detailList) {
                GeneralOutBodys bodys = new GeneralOutBodys();
                bodys.setCmaterialvid(item.getItemno());
                bodys.setNassistnum(item.getQty());
                bodys.setCstateid(cstateid);
                bodys.setCphh(item.getVendorbatch());
                bodys.setDproducedate(codeDate.getManufacturedate());
                bodys.setYxqz(codeDate.getExpireddate());
                bodys.setVbatchcode_vdef11("");
                bodys.setVbatchcode_vdef12(item.getBoxflag());
                bodys.setVbatchcode_vdef16(item.getBoxno());
                bodys.setPk_batchcode(CommonUtils.getBatchCode(item.getCompanycode(), item.getVendorbatch(), item.getBoxflag(), item.getBatchno()));
                bodysList.add(bodys);
            }
            ncOut.setDetailList(bodysList);
            body = JSON.toJSONString(ncOut);
            JsonResult result = sendToReviewLog.callEsbKdl(ncOut.getInitid(), gmVo.getCompanycode()+gmVo.getOrderno() + "_" + gmVo.getFromlocation(), body);
            if (result.getCode() > 0) {
                sb.append(result.getMsg());
            } else {
                //更新回写状态
                if(updateStatus) {
                    DynamicDataSource.setDataSource("sinesys");
                    UpdateWrapper<KdlGM> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("status", Constants.NC_SUBMIT_STATUS).eq("orderno", gmVo.getOrderno()).eq("companycode", gmVo.getCompanycode()).eq("fromlocation", gmVo.getFromlocation());
                    kdlGMMapper.update(new KdlGM(), updateWrapper);
                }

            }
        }
        return StringUtils.isEmpty(sb.toString())?JsonResult.success():JsonResult.error(sb.toString());
    }

    /*
     * 康德乐其他出入库回传记录回写NC
     * */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult submitGeneralInToNC(String orderno,boolean useToFlag) {
        String body = "";
        StringBuilder sb = new StringBuilder();
        Map<String,Object> paramOrder = new HashMap<>();
        paramOrder.put("orderno",orderno);
        List<KdlGM> entityList = kdlGMMapper.selectByMap(paramOrder);
        if(entityList.size()==0)
        {
            return JsonResult.error("无效的物料凭证号:"+orderno);
        }
        KdlGM entity = entityList.get(0);
        //检查制单人、审批人是否配置
        String billMaker = getNCUserId("GM",DataSourceType.SINESYS);
        if(StringUtils.isEmpty(billMaker)){
            return JsonResult.error("移库结果回传GM对应的制单人未配置");
        }
        String batchcode="";
        //检查仓库库存状态是否配置
        String cstateid = getStockStatus(entity.getPlant(),entity.getTolocation());
        if(StringUtils.isEmpty(cstateid)){
            return JsonResult.error("工厂:"+entity.getPlant()+"仓库:"+entity.getFromlocation()+"不存在对应的库存状态");
        }
        //检查批号是否有效
        BatchCodeDate codeDate = getBatchCodeDate(entity.getItemno(),entity.getVendorbatch());
        if(StringUtils.isNull(codeDate)){
            log.info("采购入库质检回传中不存在对应的生产批号："+entity.getVendorbatch());
            return JsonResult.error("采购入库质检回传中不存在对应的生产批号："+entity.getVendorbatch());
        }

        List<GeneralOutBodys> bodysList = new ArrayList<>();
        List<KdlGMVo> companyList = kdlGMMapper.getOtherInCompanyList(orderno);
        for (KdlGMVo gmVo:companyList) {
            bodysList.clear();
            NCGeneralOut ncOut = new NCGeneralOut();
            ncOut.setInitid("GeneralIn");
            ncOut.setVbillcode(gmVo.getOrderno());
            ncOut.setDbilldate(entity.getOrderdate());
            ncOut.setCtrantypeid("4A-Cxx-1183-02");
            ncOut.setVnote("");
            ncOut.setCwarehouseid(gmVo.getPlant() + gmVo.getTolocation());
            ncOut.setPk_org(CommonConfig.kdlOrgCode);
            ncOut.setBillmaker(billMaker);
            ncOut.setApprover(billMaker);
            ncOut.setCbizid(billMaker);
            List<KdlGMVo> detailList = kdlGMMapper.getCompanyGMOtherInDetailList(entity.getOrderno(),gmVo.getCompanycode(),gmVo.getTolocation());
            for (KdlGMVo item : detailList) {
                GeneralOutBodys bodys = new GeneralOutBodys();
                bodys.setCmaterialvid(item.getItemno());
                bodys.setNassistnum(item.getQty());
                bodys.setCstateid(cstateid);
                bodys.setCphh(item.getVendorbatch());
                bodys.setDproducedate(codeDate.getManufacturedate());
                bodys.setYxqz(codeDate.getExpireddate());
                if(useToFlag) {
                    bodys.setVbatchcode_vdef11(item.getBatchnoto());
                    bodys.setVbatchcode_vdef12(item.getBoxflagto());
                    bodys.setVbatchcode_vdef16(item.getBoxnoto());
                    bodys.setPk_batchcode(CommonUtils.getBatchCode(item.getCompanycode(), item.getVendorbatch(), item.getBoxflagto(), item.getBatchnoto()));
                }else{
                    bodys.setVbatchcode_vdef11(item.getBatchno());
                    bodys.setVbatchcode_vdef12(item.getBoxflag());
                    bodys.setVbatchcode_vdef16(item.getBoxno());
                    bodys.setPk_batchcode(CommonUtils.getBatchCode(item.getCompanycode(), item.getVendorbatch(), item.getBoxflag(), item.getBatchno()));
                }
                bodysList.add(bodys);
            }
            ncOut.setDetailList(bodysList);
            body = JSON.toJSONString(ncOut);
            JsonResult result = sendToReviewLog.callEsbKdl(ncOut.getInitid(), entity.getOrderno() + "_" + entity.getFromlocation(), body);
            if (result.getCode() > 0) {
                sb.append(result.getMsg());
            } else {
                //更新回写状态
                DynamicDataSource.setDataSource("sinesys");
                UpdateWrapper<KdlGM> updateWrapper = new UpdateWrapper<>();
                updateWrapper.set("status", Constants.NC_SUBMIT_STATUS).eq("orderno", gmVo.getOrderno()).eq("companycode", gmVo.getCompanycode()).eq("tolocation", gmVo.getTolocation());
                kdlGMMapper.update(new KdlGM(), updateWrapper);

            }
        }
        return StringUtils.isEmpty(sb.toString())?JsonResult.success():JsonResult.error(sb.toString());
    }

    /**
     * 信谊移库指令下发至康德乐
     * @param id 移库指令记录id
     * @return
     */
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult uploadGoodsmovement(Integer id) {
        String body = "";
        StringBuilder sb = new StringBuilder();
        KdlSineGoodsmovement entity = kdlSineGoodsmovementMapper.selectById(id);
        if(StringUtils.isNull(entity))
        {
            return JsonResult.error("无效的id:"+id.toString());
        }
        List<KdlSineGoodsmovementB> detailList = kdlSineGoodsmovementMapper.getMovementDetail(id);
        NCGeneralOut ncOut = null;
        GeneralOutBodys bodys = null;
        String batchcode="";
        try {
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + entity.getPrincipalid() + "</PrincipalID>");
            sb.append("<PrincipalOrderNo>"+entity.getOrderno()+"</PrincipalOrderNo>");
            sb.append("<OrderType>" + entity.getOrdertype() + "</OrderType>");
            sb.append("<OrderDate>" +DateUtils.formatDate(entity.getOrderdate()) + "</OrderDate>");
            sb.append("<Plant>" + entity.getPlant() + "</Plant>");
            sb.append("</Head>");
            sb.append("<Details>");
            Integer rowIndex = 0;
            for (KdlSineGoodsmovementB detail:detailList) {
                sb.append("<Detail>");
                rowIndex++;
                sb.append("<SN>" + rowIndex.toString() + "</SN>");
                sb.append("<ItemNo>" + detail.getItemno() + "</ItemNo>");
                sb.append("<VendorBatch>" + detail.getVendorbatch() + "</VendorBatch>");
                sb.append("<ManufactureDate>" + DateUtils.formatDate(detail.getManufacturedate()) + "</ManufactureDate>");
                sb.append("<ExpiredDate>" + DateUtils.formatDate(detail.getExpireddate()) + "</ExpiredDate>");
                sb.append("<Qty>" + detail.getQty() + "</Qty>");
                sb.append("<FromLocation>" + detail.getFromlocation() + "</FromLocation>");
                sb.append("<ToLocation>" + detail.getTolocation() + "</ToLocation>");
                sb.append("<Text>" + detail.getText() + "</Text>");
                sb.append("<BoxFlag>" + detail.getBoxflag() + "</BoxFlag>");
                sb.append("<BoxNo>" + detail.getBoxno().replace("&","&amp;") + "</BoxNo>");
                sb.append("</Detail>");
            }
            sb.append("</Details>");
            sb.append("</CAH3PL>");
            body = sb.toString();
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            log.setSubmitNo(entity.getOrderno());

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox?SHYPConstants.KDL_UPLOADGOODSMOVEMENT_URL_SUFFIX_TEST: SHYPConstants.KDL_UPLOADGOODSMOVEMENT_URL_SUFFIX, "", null, body, config.getUseSandbox());
                //result = "<?xml version=\"1.0\" encoding=\"utf-8\"?><CAH3PL><Head><FunCode>9000</FunCode><Remark>读取数据成功</Remark><DocType>GM</DocType></Head><Details><Detail><OrderNo>4911568514</OrderNo><PrincipalOrderNo/><DOCNo>0000000063877638</DOCNo><Ordertype>311</Ordertype><SN>0001</SN><ItemNo>0119020401</ItemNo><BatchNo>0006403221</BatchNo><QTY>5000.000</QTY><Unit>EA</Unit><FromLocation>1012</FromLocation><ToLocation>1001</ToLocation><Plant>T150</Plant><Date>20240130</Date><GmName>吕 天成</GmName><VendorBatch>230132</VendorBatch><BoxFlag>ZX</BoxFlag><BoxNo/></Detail></Details></CAH3PL>";
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                Element headResult = XmlUtil.getElement(elementG, "Head");
                String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                log.setResponseBody(result);
                log.setResponseCode(resCode);
                log.setResponseResult(resRemark);
                ncServiceLogService.save(log);
                if (!"9000".equals(resCode)) {
                    sbResult.append(resRemark);
                }else
                {
                    entity.setStatus("已下发");
                    kdlSineGoodsmovementMapper.updateById(entity);
                }
                        //解析返回的数据并保存
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult saveFeedback(KdlQffFeedback entity) {
        UpdateWrapper<KdlQffFeedback> queryWrapper = new UpdateWrapper<>();
        queryWrapper.set("status","已处理").set("tolocation",entity.getTolocation()).set("feedback",entity.getFeedback())
                .set("oper_user",ShiroUtils.getUserName()).set("oper_time",DateUtils.now())
                .eq("id",entity.getId());
        kdlQffFeedbackMapper.update(new KdlQffFeedback(),queryWrapper);
        return JsonResult.success();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult saveTransOperator(KdlTransReport entity) {
        UpdateWrapper<KdlTransReport> queryWrapper = new UpdateWrapper<>();
        queryWrapper.set("consignor1",entity.getConsignor1()).set("consignor2",entity.getConsignor2()).set("operator2",entity.getOperator2())
                .set("plate_no",entity.getPlate_no())
                .eq("id",entity.getId());
        kdlTransReportMapper.update(new KdlTransReport(),queryWrapper);
        return JsonResult.success();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult saveTransVendor(KdlTransDto dto) {
        if(StringUtils.isNull(dto)){
            return JsonResult.error("承运商档案数据为空");
        }
        KdlTransVendor entity = dto.getVendor();
        if(StringUtils.isNull(entity)){
            return JsonResult.error("承运商档案数据为空");
        }
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
            entity.setUpdateTime(DateUtils.now());
            kdlTransVendorMapper.updateById(entity);
        } else {
            entity.setMark(1);
            entity.setCreateTime(DateUtils.now());
            kdlTransVendorMapper.insert(entity);

        }
        Map<String,Object> param = new HashMap<>();
        param.put("pid",entity.getId());

        if(dto.getVendorOpers()!=null && dto.getVendorOpers().length>0){
            kdlTransVendorOperMapper.deleteByMap(param);
            for (KdlTransVendorOper oper:dto.getVendorOpers()) {
                oper.setMark(1);
                oper.setPid(entity.getId());
                oper.setCreateTime(DateUtils.now());
                kdlTransVendorOperMapper.insert(oper);
            }
        }
        if(dto.getVendorTrucks()!=null && dto.getVendorTrucks().length>0){
            kdlTransVendorTruckMapper.deleteByMap(param);
            for (KdlTransVendorTruck truck:dto.getVendorTrucks()) {
                truck.setMark(1);
                truck.setPid(entity.getId());
                truck.setCreateTime(DateUtils.now());
                kdlTransVendorTruckMapper.insert(truck);
            }
        }
        return JsonResult.success();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult saveTransVendorOper(KdlTransVendorOper entity) {
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
            entity.setUpdateTime(DateUtils.now());
            kdlTransVendorOperMapper.updateById(entity);
        } else {
            entity.setMark(1);
            entity.setCreateTime(DateUtils.now());
            kdlTransVendorOperMapper.insert(entity);
        }
        return JsonResult.success();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult saveTransVendorTruck(KdlTransVendorTruck entity) {
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
            entity.setUpdateTime(DateUtils.now());
            kdlTransVendorTruckMapper.updateById(entity);
        } else {
            entity.setMark(1);
            entity.setCreateTime(DateUtils.now());
            kdlTransVendorTruckMapper.insert(entity);
        }
        return JsonResult.success();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult uploadExceptionFeedback(Integer id) {
        String body = "";
        StringBuilder sb = new StringBuilder();
        KdlQffFeedback entity = kdlQffFeedbackMapper.selectById(id);
        if(StringUtils.isNull(entity))
        {
            return JsonResult.error("无效的id:"+id.toString());
        }
        try {
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + entity.getPrincipalid() + "</PrincipalID>");
            sb.append("<PrincipalOrderNo>"+entity.getPrincipalorderno()+"</PrincipalOrderNo>");
            sb.append("<OrderType>OFF</OrderType>");
            sb.append("<OrderDate>" +DateUtils.formatDate(entity.getErdat()) + "</OrderDate>");
            sb.append("<QFFNo>"+entity.getQffno()+"</QFFNo>");
            sb.append("<Inspectiontype>" + entity.getInspectiontype() + "</Inspectiontype>");
            sb.append("<Plant>" + entity.getPlant() + "</Plant>");
            sb.append("</Head>");
            sb.append("<Details>");
            Integer rowIndex = 0;
                sb.append("<Detail>");
            sb.append("<CHARG>" + entity.getBatch() + "</CHARG>");
            sb.append("<ItemNo>" + entity.getItemno() + "</ItemNo>");
                sb.append("<VendorBatch>" + entity.getVendorbatch() + "</VendorBatch>");
                sb.append("<ManufactureDate>" + DateUtils.formatDate(entity.getManufacturedate()) + "</ManufactureDate>");
            sb.append("<ExpiredDate>" + DateUtils.formatDate(entity.getExpireddate()) + "</ExpiredDate>");
                sb.append("<Qty>" + entity.getQty() + "</Qty>");
                sb.append("<OrderNo>" + entity.getOrderno() + "</OrderNo>");
                sb.append("<FromLocation>" + entity.getLocation() + "</FromLocation>");
            sb.append("<ToLocation>" + entity.getTolocation() + "</ToLocation>");
                sb.append("<ERDAT>"+DateUtils.formatDate(entity.getErdat())+"</ERDAT>");
            sb.append("<Text>" + entity.getFeedback() + "</Text>");
            sb.append("<BoxFlag>" + entity.getBoxflag() + "</BoxFlag>");
            sb.append("<BoxNo>" + entity.getBoxno().replaceAll("&","&amp;") + "</BoxNo>");
                sb.append("</Detail>");
            sb.append("</Details>");
            sb.append("</CAH3PL>");
            body = sb.toString();
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            log.setSubmitNo(entity.getQffno());

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox?SHYPConstants.KDL_UPLOADEXCEPTIONFEEDBACK_URL_SUFFIX_TEST: SHYPConstants.KDL_UPLOADEXCEPTIONFEEDBACK_URL_SUFFIX, "", null, body, config.getUseSandbox());
                //result = "<?xml version=\"1.0\" encoding=\"utf-8\"?><CAH3PL><Head><FunCode>9000</FunCode><Remark>读取数据成功</Remark><DocType>GM</DocType></Head><Details><Detail><OrderNo>4911568514</OrderNo><PrincipalOrderNo/><DOCNo>0000000063877638</DOCNo><Ordertype>311</Ordertype><SN>0001</SN><ItemNo>0119020401</ItemNo><BatchNo>0006403221</BatchNo><QTY>5000.000</QTY><Unit>EA</Unit><FromLocation>1012</FromLocation><ToLocation>1001</ToLocation><Plant>T150</Plant><Date>20240130</Date><GmName>吕 天成</GmName><VendorBatch>230132</VendorBatch><BoxFlag>ZX</BoxFlag><BoxNo/></Detail></Details></CAH3PL>";
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                Element headResult = XmlUtil.getElement(elementG, "Head");
                String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                log.setResponseBody(result);
                log.setResponseCode(resCode);
                log.setResponseResult(resRemark);
                String datasource = DynamicDataSource.getDataSource();
                DynamicDataSource.setDataSource("system");
                ncServiceLogService.save(log);
                DynamicDataSource.setDataSource(datasource);

                if ("9000".equals(resCode) || resRemark.contains("已存在")) {
                    UpdateWrapper<KdlQffFeedback> updateWrapper= new UpdateWrapper<>();
                    updateWrapper.set("status","已反馈").eq("id",entity.getId());
                    kdlQffFeedbackMapper.update(new KdlQffFeedback(),updateWrapper);
                }else
                {
                    sbResult.append(resRemark);
                }
                //解析返回的数据并保存
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult uploadOutbound(Integer id) {
        String body = "";
        StringBuilder sb = new StringBuilder();
        KdlSineSoOutbound entity = kdlSineSoOutboundMapper.selectById(id);
        if(StringUtils.isNull(entity))
        {
            return JsonResult.error("无效的id:"+id.toString());
        }
        List<KdlSineSoOutboundB> detailList = kdlSineSoOutboundMapper.getOutboundDetail(id);
        try {
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sb.append("<CAH3PL>");
            sb.append("<Head>");
            sb.append("<PrincipalID>" + entity.getPrincipalid() + "</PrincipalID>");
            sb.append("<SalesOrderNo>"+entity.getSalesorderno()+"</SalesOrderNo>");
            sb.append("<DeliveryOrderNo>"+entity.getSalesorderno()+"</DeliveryOrderNo>");
//            sb.append("<DeliveryOrderNo>"+entity.getDeliveryorderno()+"</DeliveryOrderNo>");
            sb.append("<OrderType>" + entity.getOrdertype() + "</OrderType>");
            sb.append("<OrderDate>" +DateUtils.formatDate(entity.getOrderdate()) + "</OrderDate>");
            if(!StringUtils.isEmpty(entity.getExpecteddeliverydate())) {
                sb.append("<ExpectedDeliveryDate>" + DateUtils.formatDate(entity.getExpecteddeliverydate()) + "</ExpectedDeliveryDate>");
            }else
            {
                sb.append("<ExpectedDeliveryDate></ExpectedDeliveryDate>");
            }
            sb.append("<CustomerCode>" + entity.getCustomercode() + "</CustomerCode>");
            sb.append("<contact>" + entity.getContact() + "</contact>");
            sb.append("<Tel>" + entity.getTel() + "</Tel>");
            sb.append("<DeliveryAddress>" + entity.getDeliveryaddress() + "</DeliveryAddress>");
            sb.append("<Remark>" + entity.getRemark() + "</Remark>");
            sb.append("</Head>");
            sb.append("<Details>");
            Integer rowIndex = 0;
            for (KdlSineSoOutboundB detail:detailList) {
                sb.append("<Detail>");
                rowIndex++;
                sb.append("<SOLineNo>" +  rowIndex.toString() + "</SOLineNo>");
                sb.append("<DNLineNo>" +detail.getSolineno() + "</DNLineNo>");
                sb.append("<BoxFlag>" + detail.getBoxflag() + "</BoxFlag>");
                sb.append("<BoxNo>" + detail.getBoxno() + "</BoxNo>");
                sb.append("<ItemCode>" + detail.getItemcode() + "</ItemCode>");
                sb.append("<Plant>" + detail.getPlant() + "</Plant>");
                sb.append("<Qty>" + detail.getQty() + "</Qty>");
                sb.append("<UOM>" + detail.getUom() + "</UOM>");
                sb.append("<Batch>" + detail.getBatch() + "</Batch>");
                sb.append("<SerialNo></SerialNo>");
                sb.append("</Detail>");
            }
            sb.append("</Details>");
            sb.append("</CAH3PL>");
            body = sb.toString();
            DDKJConfig config = new KDLConfig();
            config.setUseSandbox(CommonConfig.kdlSandbox);
            KDLRequest request = null;
            request = new KDLRequest(config);
            String postData = "";
            String result = "";
            NcServiceLog log = new NcServiceLog();
            //String danj_no = dto.body.length>0?dto.body[0].getDanj_no():"";
            log.setSubmitNo(entity.getSalesorderno());

            log.setRequestBody(body);
            StringBuilder sbResult = new StringBuilder();
            log.setSubmitTime(DateUtils.now());
            try {
                result = request.postData(CommonConfig.kdlSandbox ? SHYPConstants.KDL_UPLOADOUTBOUND_URL_SUFFIX_TEST : SHYPConstants.KDL_UPLOADOUTBOUND_URL_SUFFIX, "", null, body, config.getUseSandbox());
                //result = "<?xml version=\"1.0\" encoding=\"utf-8\"?><CAH3PL><Head><FunCode>9000</FunCode><Remark>读取数据成功</Remark><DocType>GM</DocType></Head><Details><Detail><OrderNo>4911568514</OrderNo><PrincipalOrderNo/><DOCNo>0000000063877638</DOCNo><Ordertype>311</Ordertype><SN>0001</SN><ItemNo>0119020401</ItemNo><BatchNo>0006403221</BatchNo><QTY>5000.000</QTY><Unit>EA</Unit><FromLocation>1012</FromLocation><ToLocation>1001</ToLocation><Plant>T150</Plant><Date>20240130</Date><GmName>吕 天成</GmName><VendorBatch>230132</VendorBatch><BoxFlag>ZX</BoxFlag><BoxNo/></Detail></Details></CAH3PL>";
                Document docResult = XmlUtil.readXML(result);
                Element elementG = XmlUtil.getRootElement(docResult);
                Element headResult = XmlUtil.getElement(elementG, "Head");
                String resCode = CommonUtils.XmlGetNodeContent(headResult, "FunCode");
                String resRemark = CommonUtils.XmlGetNodeContent(headResult, "Remark");

                log.setResponseBody(result);
                log.setResponseCode(resCode);
                log.setResponseResult(resRemark);
                String datasource = DynamicDataSource.getDataSource();
                DynamicDataSource.setDataSource("system");
                ncServiceLogService.save(log);
                DynamicDataSource.setDataSource(datasource);
                if (!"9000".equals(resCode)) {
                    sbResult.append(resRemark);
                } else
                {
                    UpdateWrapper<KdlSineSoOutbound> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("status",Constants.KDL_SUBMIT_STATUS).eq("id",id);
                    kdlSineSoOutboundMapper.update(new KdlSineSoOutbound(),updateWrapper);
                }
                //解析返回的数据并保存
                return StringUtils.isEmpty(sbResult.toString())?JsonResult.success():JsonResult.error(sbResult.toString());

            } catch (Exception ex) {
                log.setResponseBody(ex.getMessage());
                log.setResponseCode("500");
                log.setResponseResult("");
                ncServiceLogService.save(log);
                return JsonResult.error(StringUtils.isEmpty(result) ? ex.getMessage() : result);

            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage());
        }
    }

    @Override
    public JsonResult getFtpFile(String remoteFileName, String savePath) {
        boolean result = ftpUtil.downloadFile(CommonConfig.kdlSftpQFFPath,remoteFileName,savePath);
        return result?JsonResult.success():JsonResult.error();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public List<KDLMaterial> getMaterialUploadList() {
        return kdlMaterialMapper.selectList(new QueryWrapper<KDLMaterial>().eq("status",0).eq("fcbz","N"));
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public List<KDLCustomer> getCustomerUploadList() {
        return kdlCustomerMapper.selectList(new QueryWrapper<KDLCustomer>().eq("status",0).eq("fcbz","N"));
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public List<KDLSupplier> getSupplierUploadList() {
        return kdlSupplierMapper.selectList(new QueryWrapper<KDLSupplier>().eq("status",0).eq("fcbz","N"));
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public List<KdlStoredoc> getPlantList() {
        return kdlStoredocMapper.getPlantList();
    }
    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public List<KdlStoredoc> getBincodeList(String plant) {
        return kdlStoredocMapper.getBincodeList(plant);
    }


    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getRegionList() {
        return JsonResult.success(kdlCustomerMapper.getRegionList());
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public List<KdlQffAttach> getQffAttachList() {
        return kdlQffFeedbackMapper.getQffAttachList();
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public boolean updateDownloadStatus(Integer id, String status) {
        try
        {
            kdlQffAttachMapper.updateDownloadStatus(id,status);
            return true;
        }
        catch(Exception ex) {
            log.error(ex.getMessage());
            return false;
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getFeedbackAttachList(String qffno) {
        return JsonResult.success(kdlQffAttachMapper.getAttachList(qffno));
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getTransVendorList(BaseQuery query) {
        KdlTransVendorQuery ncpoOrderQuery = (KdlTransVendorQuery)query;
        IPage<KdlTransVendor> page = new Page<>(ncpoOrderQuery.getPage(), ncpoOrderQuery.getLimit());
        IPage<KdlTransVendor> pageData = kdlTransVendorMapper.getTransVendorList(page, ncpoOrderQuery);
        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getTransVendorOperList(BaseQuery query) {
        KdlTransVendorQuery vendorQuery = (KdlTransVendorQuery)query;
        return JsonResult.success(kdlTransVendorMapper.getTransVendorOperList(vendorQuery.getPid()));
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getVendorOperListByName(BaseQuery query) {
        KdlTransVendorQuery vendorQuery = (KdlTransVendorQuery)query;
        return JsonResult.success(kdlTransVendorMapper.getVendorOperListByName(vendorQuery.getVendor()));
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getTransVendorTruckList(BaseQuery query) {
        KdlTransVendorQuery vendorQuery = (KdlTransVendorQuery)query;
        return JsonResult.success(kdlTransVendorMapper.getTransVendorTruckList(vendorQuery.getPid()));
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getVendorTruckListByName(BaseQuery query) {
        KdlTransVendorQuery vendorQuery = (KdlTransVendorQuery)query;
        return JsonResult.success(kdlTransVendorMapper.getVendorTruckListByName(vendorQuery.getVendor()));
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getQCUserList(String masterdataType) {
        if("M".equals(masterdataType)){
            return JsonResult.success(kdlMaterialMapper.getQCUserList());
        }else if("C".equals(masterdataType)){
            return JsonResult.success(kdlCustomerMapper.getQCUserList());
        }else{
            return JsonResult.success(kdlSupplierMapper.getQCUserList());
        }
    }

    @Override
    public JsonResult manualsync(KdlManualSync entity) {

        try {
            //解析xml请求报文
            Document docResult = XmlUtil.readXML(entity.getRequestBody());
            Element elementG = XmlUtil.getRootElement(docResult);
            Element headResult = XmlUtil.getElement(elementG, "Head");
            String kdlcode = CommonUtils.XmlGetNodeContent(headResult, "DocType");
            String startTime = CommonUtils.XmlGetNodeContent(headResult, "StartTime");
            String endTime = CommonUtils.XmlGetNodeContent(headResult, "EndTime");
            if(kdlcode.toUpperCase().equals("Z01-KDL")){
                //请求采购质检入库
                KdlPurchaseinQuery query = new KdlPurchaseinQuery();
                query.setDoctype(kdlcode);
                query.setPrincipalid(CommonConfig.kdlCompanyId);
                query.setStarttime(startTime);
                query.setEndtime(endTime);

                return kdlPurchaseinService.syncPurchase(query);
            }else if (kdlcode.toUpperCase().equals("ZST3")){
                //销售出库质检
                KdlPurchaseinReturnQuery query = new KdlPurchaseinReturnQuery();
                query.setDoctype(kdlcode);
                query.setPrincipalid(CommonConfig.kdlCompanyId);
                query.setStarttime(startTime);
                query.setEndtime(endTime);
                return kdlPurchaseinReturnService.syncPurchaseReturn(query);
            }
            else if (kdlcode.toUpperCase().equals("Z04-KDL")){
                //销售出库质检
                KdlCallBaseQuery query = new KdlCallBaseQuery();
                query.setPrincipalid(CommonConfig.kdlCompanyId);
                query.setDoctype(kdlcode);
                query.setStarttime(startTime);
                query.setEndtime(endTime);
                return kdlSaleOutQcService.syncSaleOutQC(query);
            }else if (kdlcode.toUpperCase().equals("Z05-KDL")){
                //销退回传
                KdlZ05kdlQuery query = new KdlZ05kdlQuery();
                query.setPrincipalid(CommonConfig.kdlCompanyId);
                query.setDoctype(kdlcode);
                query.setStarttime(startTime);
                query.setEndtime(endTime);
                return kdlZ05kdlService.syncSaleReturn(query);
            }else if (kdlcode.toUpperCase().equals("WE")){
                //采购收货
                KdlPurchaseweQuery query = new KdlPurchaseweQuery();
                query.setPrincipalid(CommonConfig.kdlCompanyId);
                query.setDoctype(kdlcode);
                query.setStarttime(startTime);
                query.setEndtime(endTime);
                return syncPurchasewe(query);
            }else if (kdlcode.toUpperCase().equals("GM")){
                //采购收货
                KdlGMQuery query = new KdlGMQuery();
                query.setPrincipalid(CommonConfig.kdlCompanyId);
                query.setDoctype(kdlcode);
                query.setStarttime(startTime);
                query.setEndtime(endTime);
                return kdlGMService.syncGM(query);
            }
            else if (kdlcode.toUpperCase().equals("POD")){
                //签收
                RGRQuery query = new RGRQuery();
                query.setPrincipalid(CommonConfig.kdlCompanyId);
                query.setDoctype(kdlcode);
                query.setStarttime(startTime);
                query.setEndtime(endTime);
                return syncPOD(query);
            }else if (kdlcode.toUpperCase().equals("RGR")){
                //拒收订单
                RGRQuery query = new RGRQuery();
                query.setPrincipalid(CommonConfig.kdlCompanyId);
                query.setDoctype(kdlcode);
                query.setStarttime(startTime);
                query.setEndtime(endTime);
                return syncRGR(query);
            }else if (kdlcode.toUpperCase().equals("QFF")){
                //异常反馈
                QffFeedbackQuery query = new QffFeedbackQuery();
                query.setPrincipalid(CommonConfig.kdlCompanyId);
                query.setDoctype(kdlcode);
                query.setStarttime(startTime);
                query.setEndtime(endTime);
                return syncQffFeedback(query);
            }else if (kdlcode.toUpperCase().equals("Inventory")){
                //康德乐实时库存
                Element details = XmlUtil.getElement(elementG, "Details");
                Element detail = null;
                for (int j = 0; j < details.getChildNodes().getLength(); j++) {
                    if (elementG.getChildNodes().item(j).getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    detail = (Element) details.getChildNodes().item(j);
                    break;
                }
                String plant = CommonUtils.XmlGetNodeContent(headResult, "Plant");
                String materialCode = CommonUtils.XmlGetNodeContent(detail, "Material");
                String vendorBatch = CommonUtils.XmlGetNodeContent(detail, "VenderBatch");
                KdlInventoryQuery query = new KdlInventoryQuery();
                query.setPrincipalid(CommonConfig.kdlCompanyId);
                query.setDoctype(kdlcode);
                query.setPlant(plant);
                query.setMaterial(materialCode);
                query.setVendorbatch(vendorBatch);
                return syncInventory(query);
            }else if (kdlcode.toUpperCase().equals("INST")){
                //养护记录
                QffFeedbackQuery query = new QffFeedbackQuery();
                query.setPrincipalid(CommonConfig.kdlCompanyId);
                startTime = CommonUtils.XmlGetNodeContent(headResult, "FROMDATE");
                endTime = CommonUtils.XmlGetNodeContent(headResult, "TODATE");
                query.setDoctype(kdlcode);
                query.setStarttime(startTime);
                query.setEndtime(endTime);
                return syncMaintainReport(query);
            }else if (kdlcode.toUpperCase().equals("ZTRN")){
                //养护记录
                Element detail = null;
                Element details = XmlUtil.getElement(elementG, "Details");
                for (int j = 0; j < details.getChildNodes().getLength(); j++) {
                    if (elementG.getChildNodes().item(j).getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    detail = (Element) details.getChildNodes().item(j);
                    break;
                }

                startTime = CommonUtils.XmlGetNodeContent(detail, "FROMDATE");
                endTime = CommonUtils.XmlGetNodeContent(detail, "TODATE");
                QffFeedbackQuery query = new QffFeedbackQuery();
                query.setPrincipalid(CommonConfig.kdlCompanyId);
                query.setDoctype(kdlcode);
                query.setStarttime(startTime);
                query.setEndtime(endTime);
                return syncTransReport(query);
            }else if (kdlcode.toUpperCase().equals("MARA")){
                //主数据审批
                KdlMaraQuery query = new KdlMaraQuery();
                String masterType = CommonUtils.XmlGetNodeContent(headResult, "MasterType");
                query.setPrincipalid(CommonConfig.kdlCompanyId);
                query.setDoctype(kdlcode);
                query.setMastertype(masterType);
                query.setStarttime(startTime);
                query.setEndtime(endTime);
                return syncMasterDataResult(query);
            }else
            {
                return JsonResult.error("位置的接口类型");
            }
        }
        catch(Exception ex)
        {
            return JsonResult.error(ex.getMessage()==null?"":ex.getMessage());
        }
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getKdlchgList(BaseQuery query) {
        KDLchgQuery kdLchgQuery = (KDLchgQuery) query;
        IPage<KdlHC> page = new Page<>(kdLchgQuery.getPage(), kdLchgQuery.getLimit());
        IPage<KdlHC> pageDate = kdlHCMapper.getKdlchgList(page, kdLchgQuery);

        return JsonResult.success(pageDate);
    }
}
